[Python-3000] Unbound methods -- keep creating API?

Christian Heimes lists at cheimes.de
Mon Nov 26 17:19:37 CET 2007

Greg Ewing wrote:
> This needs consideration. Pyrex currently makes use of
> this behaviour when defining a Python class having Pyrex
> functions as methods.
> However, a better solution for Pyrex would be to add
> method-binding behaviour to the C function object, so
> that C functions can be used directly as methods. The
> above example would then work simply by doing
>    Example.id = id

A C function binder is very easy to implement. Here is a rough

class binder:
    def __init__(self, func):
        self._func = func
    def __get__(self, obj, type):
        if obj:
            return wrapper(self._func, obj)
            return self._func

def wrapper(func, obj):
    def wrapped(*args, **kwargs):
        return func(obj, *args, **kwargs)
    return wrapped

class Example:
    id = binder(id)

>>> Example.id
<built-in function id>
>>> Example().id()
>>> Example().id
<function wrapped at 0x83ac714>

More information about the Python-3000 mailing list