[Python-3000] A minor cleanup: instances from bound methods

Nick Craig-Wood nick at craig-wood.com
Tue Apr 18 11:02:15 CEST 2006


I noticed this the other day.  Perhaps it is suitable for a python
3000 cleanup?  It certainly seems illogical, but probably too
intrusive to change in python 2.x.

I needed to find the instance from a bound method, with obj.im_self.
Eg

  >>> class C(object):
  ...     def fn(self): print "hello"
  ... 
  >>> c=C()
  >>> fn=c.fn
  >>> fn
  <bound method C.fn of <__main__.C object at 0xb7dd2acc>>
  >>> fn.im_self
  <__main__.C object at 0xb7dd2acc>
  >>> fn.__self__
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  AttributeError: 'function' object has no attribute '__self__'
  >>>

But I discovered that builtin objects work in a completely different
way with obj.__self__, Eg

  >>> fd=open("myfile","w")
  >>> fn=fd.write
  >>> fn
  <built-in method write of file object at 0xb7dc1260>
  >>> fn.im_self
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  AttributeError: 'builtin_function_or_method' object has no attribute 'im_self'
  >>> fn.__self__
  <open file 'myfile', mode 'w' at 0xb7dc1260>
  >>> 

I suggest that either im_self or __self__ is renamed!

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick


More information about the Python-3000 mailing list