2

So this question got me thinking. I did some testing with multiple file handles for the same file, and found some odd results that I was hoping someone could explain.

>>> f1 = open("test.txt",'w')
>>> f1.close()
>>> f1, f2 = open("test.txt", 'w'), open("test.txt", 'w')
>>> f1 == f2
False
>>> f1, f2 = open("test.txt", 'r'), open("test.txt", 'r')
>>> f1 == f2
False

Why do these tests not return True? Surely assigning a handle to the same file should have the same value.

What's the underlying mechanism for these comparisons to return False and what is the rationale for creating this behavior?

Community
  • 1
  • 1
wnnmaw
  • 5,444
  • 3
  • 38
  • 63
  • I think the 'f1 == f2' is simply comparing the object 'f1' and 'f2' and they are definitely not the same, isn't it? – Jerry Meng Apr 18 '14 at 14:39
  • `Surely assigning a handle to the same file should have the same value.` No. Why? – njzk2 Apr 18 '14 at 14:39
  • @njzk2, because the return of the ```open()``` function is the same object – wnnmaw Apr 18 '14 at 14:41
  • `the same object` as you have pointed out yourself, not it is not the same object (since `f1 == f2 -> False`) – njzk2 Apr 18 '14 at 14:42
  • You new example just show that '6 == 6', and it is true, of course. But it has nothing to do with your first example. – Jerry Meng Apr 18 '14 at 14:43
  • @njzk2, right, yes, the observed behavior tells me they are not, but its not what I expected so I'm looking for an explanation as to why – wnnmaw Apr 18 '14 at 14:43
  • @JerryMeng, hmm, yeah, not a good example – wnnmaw Apr 18 '14 at 14:45
  • 3
    two handles opened on a file are different. they may point to different places of the file (in your `r` example, try to read from f1 and from f2, you'll read the same line twice, showing that f1 has advanced in the file, but f2 has not). – njzk2 Apr 18 '14 at 14:45
  • 1
    So basically, you create TWO objects independently. The only reason you may think they are same (they are not for real) is that they are the handler for same file. However, it makes no differences. We are talking about the objects (everything in Python is Object) rather than what those objects are doing. – Jerry Meng Apr 18 '14 at 14:49

1 Answers1

3

The underlying mechanism is explained here: https://docs.python.org/2/library/stdtypes.html

some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal

...

Non-identical instances of a class normally compare as non-equal unless the class defines the eq() method or the cmp() method.

Community
  • 1
  • 1
franz.fonta
  • 423
  • 4
  • 12