[Pyrex] pyrex functions to replace a method (Re: replace a method in class: how?)

Bruno Desthuilliers onurb at xiludom.gro
Wed Jun 28 06:19:13 EDT 2006


Greg Ewing wrote:
> Brian Blais wrote:
> 
>> I have found a very similar problem trying to replace a method using a
>> function defined in pyrex.
> 
> 
> Functions defined in Pyrex are C-implemented functions,
> which don't trigger the method binding magic when you
> access them through a class. The same thing happens if
> you try to use a built-in function as a method.
> 
> What *should* work is to define the method inside a
> class in Pyrex (plain class, not extension type) and
> extract it out of the class's __dict__. That's because
> Pyrex pre-wraps a function defined in a class in an
> unbound method object before putting it in the class.

Or write the needed descriptor and wrap the function in (Q&D, needs a
lot of improvements):

def CFuncWrapper(func, instance):
    def _wrappedCFunc(*args, **kw):
        return func(instance, *args, **kw)
    return _wrappedCFunc

class CFuncMethodType(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, cls=None):
        if instance:
            return CFuncWrapper(self.func, instance)
        else:
            assert(cls is not None)
            return self.func

>>> class Foo(object): pass
...
>>> Foo.isa = CFuncMethodType(isinstance)
>>> Foo.isa(Foo(), Foo)
True
>>> f.isa(list)
False
>>> f.isa(Foo)
True
>>>


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list