You created two mutable objects, then used is
to see if those are the same object. That should definitely return False
, or something would be broken.
You wouldn't ever want is
to return true here. Imagine if you did this:
foo = []
bar = []
foo.append(42)
then you'd be very surprised if bar
now contains 42
. If is
returned true, meaning that both []
invocations returned the exact same object, then appending to foo
would be visible in the reference to bar
.
For immutable objects, it makes sense to cache objects, at which point is
may return true, like with empty tuples:
>>> () is () # are these two things the same object?
True
The CPython implementation has optimised empty tuple creation; you'll always get the exact same object, because that saves memory and makes certain operations faster. Because tuples are immutable, this is entirely safe.
If you expected to test for value equality instead, then you got the wrong operator. Use the ==
operator instead:
>>> [] == [] # do these two objects have the same value?
True
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…