Id of methods

Chris Angelico rosuav at gmail.com
Thu Feb 9 05:06:21 CET 2012


On Thu, Feb 9, 2012 at 2:48 PM, Emeka <emekamicro at gmail.com> wrote:
> I am trying to see if I could get more of Python without being insane.

Oh, I thought insanity was a prerequisite... anyway.

> print Boo.__dict__
>
> {'__module__': '__main__', 'ball': <function ball at 0x286e9b0>, 'daf':
> <function daf at 0x286e938>, '__dict__ ......}
>
> print  hex(id(Boo.daf))
> 0x27de5a0
>
> My question is why is it that the id of Boo.daf  is different from daf's hex
> value in the above dict?

Take no notice of the exact value of id(). It is an opaque value that
shouldn't be relied upon for anything.

That said, though, I tried your example in my two Windows Pythons,
2.6.5 and 3.2; in 3.2, the behavior is most like what you seem to be
accepting:

>>> Boo.__dict__
dict_proxy({'__module__': '__main__', 'ball': <function ball at
0x00FCBCD8>, 'daf': <function daf at 0x00FCBC90>, '__dict__':
<attribute '__dict__' of 'Boo' objects>, '__weakref__': <attribute
'__weakref__' of 'Boo' objects>, '__doc__': None, '__init__':
<function __init__ at 0x00FCBC48>})
>>> hex(id(Boo.daf))
'0xfcbc90'
>>> Boo.daf
<function daf at 0x00FCBC90>

Same number everywhere. But 2.6.5 has a difference that might give you a hint:

>>> print Boo.__dict__
{'__module__': '__main__', 'ball': <function ball at 0x011BDC70>,
'daf': <function daf at 0x011BDC30>, '__dict__': <attribute '__dict__'
of 'Boo' objects>, '__weakref__': <attribute '__weakref__' of 'Boo'
objects>, '__doc__': None, '__init__': <function __init__ at
0x011BDBB0>}
>>> Boo.daf
<unbound method Boo.daf>

daf is not a function, it's a special object for an unbound method.
The exact identity of it is not necessarily useful; and buried inside
it is the actual function that you defined:

>>> hex(id(Boo.daf))
'0x11b5c10'
>>> hex(id(Boo.daf.im_func))
'0x11bdc30'

And that seems to be the number that's given in the repr().

But mainly, don't rely on id() for anything beyond uniqueness against
all current objects.

ChrisA



More information about the Python-list mailing list