[Python-3000] The case for unbound methods?

Anthony Tolle artomegus at gmail.com
Mon Mar 10 03:28:18 CET 2008


On Sat, Mar 8, 2008 at 8:38 PM, Steven Bethard <steven.bethard at gmail.com> wrote:
>
>  I don't see an error thrown with either the bound or unbound methods...
>

Sorry, I should have clarified. The error occurs when wrapping the
function as a descriptor, not when wrapping it with another function.
Here's an example in Python 2.5:

class add_initial_argument(object):
    def __init__(self, descriptor, callable=None):
        self.descriptor = descriptor
        self.callable = callable
    def __get__(self, obj, type=None):
        return add_initial_argument(self.descriptor,
                                    self.descriptor.__get__(obj, type))
    def __call__(self, *args, **kwargs):
        return self.callable.__call__('newarg',
                                      *args,
                                      **kwargs)

class C(object):
    @add_initial_argument
    def foo(newarg, self):
        print 'arg1: ', newarg
        print 'arg2: ', self

>>> C().foo()
arg1:  <__main__.C object at 0x00A900D0>
arg2:  newarg
>>> C.foo(C())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in __call__
TypeError: unbound method foo() must be called with C instance as first argument
 (got str instance instead)

Also notice that the bound method still got self as the first argument.

See the script example in my recent reply to Greg Ewing for why I'm
using descriptor wrapping:
http://mail.python.org/pipermail/python-3000/2008-March/012428.html


More information about the Python-3000 mailing list