Re: strange comparison result with 'is'
- From: Terry Reedy <tjreedy@xxxxxxxx>
- Date: Mon, 17 Oct 2011 13:53:13 -0400
On 10/17/2011 5:19 AM, Peter Otten wrote:
The getattr() call is just a distraction. Every x.pop attribute access
creates a new method object. In the case of
Falsex.pop is x.pop
they have to reside in memory simultaneously while in the expression
Trueid(x.pop) == id(x.pop)
a list.pop method object is created, its id() is taken (which is actually
its address) and then the method object is released so that its memory
address can be reused for the second x.pop.
So in the latter case the two method objects can (and do) share the same
address because they don't need to exist at the same time.
This has come up enough that I opened
http://bugs.python.org/issue13203
==============================================================
Newbies too often do something like (3.2.2, )
>>> id(getattr(x, 'pop')) == id(x.pop)
True
and get confused by the (invalid) result, whereas
>>> a,b=getattr(x, 'pop'),x.pop
>>> id(a)==id(b)
False
works properly. I think we should add a sentence or two or three to the id() doc, such as
Since a newly created argument object is either destroyed or becomes inaccessible before the function returns, *id(obj)* is only useful and valid if *obj* exists prior to the call and therefore after its return.
The value of an expression such as *id(666)== id(667)* is arbitrary and meaningless. The id of the first int object might or might not be reused for the second one.
====================================================================
With something like this added, we could just say 'read the id() doc'.
--
Terry Jan Reedy
.
- Follow-Ups:
- Re: strange comparison result with 'is'
- From: alex23
- Re: strange comparison result with 'is'
- Prev by Date: Re: Equal sets with unequal print and str() representations
- Next by Date: Re: Loop through a dict changing keys
- Previous by thread: Re: strange comparison result with 'is'
- Next by thread: Re: strange comparison result with 'is'
- Index(es):