how do you get the name of a dictionary?

Duncan Booth duncan.booth at invalid.invalid
Sat Aug 19 11:13:29 EDT 2006


Tim Chase wrote:

> >>> [name for name in dir() if id(eval(name)) == id(banana)]
> ['banana', 'spatula']
> 

Please, if you are going to do something like this, then please at least 
use the 'is' operator. Using id(expr1)==id(expr2) is just plain stupid: it 
will actually work in this case, but as soon as you get into a mindset of 
testing for the same object by comparing object ids you are going to shoot 
yourself in the foot.

The first of the following tests returns True, which looks sensible at 
first glance (even though it shouldn't), but what of the second one?

>>> class C:
    def method1(self): pass
    def method2(self): pass

    
>>> inst = C()
>>> id(inst.method1)==id(inst.method1)
True
>>> id(inst.method1)==id(inst.method2)
True

Much better to use 'is' and get consistent results

>>> inst.method1 is inst.method1
False

(In case I didn't make it clear, the problem in general with comparing the 
result of calling 'id' is that as soon as the first call to id returns, any 
object created when evaluating its parameter can be freed, so the second 
call to id can reuse memory and get the same answer even though the objects 
are different.)



More information about the Python-list mailing list