+ 3
Why do functions lose the identity of (hashable) objects?
Let me clarify my question with the below example : a = (-1, 10, 8) b = (-1, 10, 8) def f(x): return min(x), min(y) print(a is b) # will output True print(f(a) is f(b)) # will output False, WTF!!! And you may be surprised that that even print(f(a) is f(a)) will output False!!
3 ответов
+ 2
The Python rules specify that an implementation of Python has to ensure that two *mutable* objects have to be separate, but *immutable* objects can, but not must - fall together.
Seems like depending on the 'production path' you may get two separate immutable objects... interesting!
+ 2
The reasoning goes like this:
In Python with assignments you don't change a value, you just strip off a name sticker and stick it somewhere else.
a = 1; b = a; a = 2
a = []; b = a; a = {}
In both situations, with immutable and mutable data, there's no difference: Although you change a, b keeps its former value.
Problem is: Mutable objects have ways to change themselves by methods.
a = [1]; b = a; a.append(2)
In this case it makes an actual difference if a is actually the same object or not:
If a is actually b, b will now also have a 2 at the end (really not 'also' because it's the very same list).
So for mutables, it'd be a catastrophy if a and b were secretly molded into one object - you could destroy data with your code and wouldn't even realize.
For immutable objects, this couldn't happen. So for safety of values it doesn't matter if Python secretly only stores one object, or two, or sometimes this and sometimes that.
How that relates to hashing - sorry, no idea. :)
But it's intentional, no bug.