Hello,

I'm a GSoC student working on SWIG's Python 3 support. When doing experiment on Python 3's new features, the different behavior between binding 'function' and 'builtin_function_or_method' confused me.

As we know, unbound method is removed in Python 3. To bind a function to a class, we can directly use this instead:

MyClass.myfunc = func


But in the case of builtin function, it can't work. The below code demonstrates this:

class Test:
    pass

def afunc(*args):
    print(*args)

Test.prt = print
Test.func = afunc

t = Test()
t.prt() #nothing
t.func() #<__main__.Test object at 0xb79987ec>


I know this is not a bug, but however it is an exception in the language, what Python trying to avoid.

Since all C function in extension module is treated as builtin function or method, the problem maybe bigger than it looks like. In the SWIG's case, it originally uses new.instancemethod to generate unbound method from the C function in DLL module. The code snippet looks like this:

class TestBase(object):
    """Proxy of C++ TestBase class"""
    #some unrelated code omitted
    pass
#_test.TestBase_test is the C function in _test DLL module
TestBase.test = new.instancemethod(_test.TestBase_test,None,TestBase)

Is there a corresponding way to do it in Python 3? A workaround I found is:

from types import MethodType
class TestBase(object):
    """Proxy of C++ TestBase class"""
    def __init__(self, *args):
        #some initialization code
        ...
        self.test = MethodType(_test.TestBase_test, self)

But this changed the original code structure so the migration would be more complicated. Is there any better way to get rid of it?

Thank you a lot!

Best regards,

Haoyu Bai
4/27/2008
_______________________________________________
Python-3000 mailing list
Python-3000@python.org
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe: 
http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com

Reply via email to