[Zope-Coders] new.instancemethod behavior under py22 vs. py21

Chris McDonough chrism@zope.com
04 Jun 2003 01:33:20 -0400


I think I happened upon a bit of ExtensionClass magic that can get me
around this problem:

from MethodObject import Method
class AMethod(Method):
     def __init__(self, func):
         self.func = func
     def __call__(self, *arg, **kw):
         return self.func(*arg, **kw)

from ExtensionClass import Base
from Acquisition import ImplicitAcquisitionWrapper
class anextensionclass(Base):
    pass
def afunction(self):
    return 1
a = anextensionclass()
b = anextensionclass()
c = ImplicitAcquisitionWrapper(a, b)
m = AMethod(afunction)
v =  m.__of__(c)
print v
print v()

[chrism@james python]$ python2.1 rebindtest2.py 
<bound method ImplicitAcquirerWrapper.(?) of <anextensionclass instance
at 80e40f8>>
1

Dunno what the ramifications of doing it this way are, but it appears to
work.

On Wed, 2003-06-04 at 01:04, Chris McDonough wrote:
> Here's a bit of code that acts differently under Python 2.2 vs. Python
> 2.1:
> 
> from ExtensionClass import Base
> from Acquisition import ImplicitAcquisitionWrapper
> import new
> 
> class anextensionclass(Base):
>     pass
> 
> def afunction(self):
>     return 1
> 
> a = anextensionclass()
> b = anextensionclass()
> c = ImplicitAcquisitionWrapper(a, b)
> 
> print new.instancemethod(afunction, c, c.__class__)
> 
> Under Python 2.1.3, this code barfs with:
> 
> Traceback (most recent call last):
>   File "rebindtest.py", line 15, in ?
>     print new.instancemethod(afunction, c, c.__class__)
> TypeError: instancemethod() argument 3 must be class, not ExtensionClass
> 
> While under Python 2.2.2, it prints:
> 
> <bound method anextensionclass.afunction of <anextensionclass instance
> at 8161678>>
> 
> I suspect the difference has something to do with type/class unification
> or perhaps some special casing put into Python 2.2 wrt ExtensionClass
> objects.
> 
> In any case, given that this doesn't work under Python 2.1, can anyone
> shed some light on dynamically rebinding functions to extensionclass
> instances as methods under Python 2.1?
> 
> - C
>   
> 
> 
> _______________________________________________
> Zope-Coders mailing list
> Zope-Coders@zope.org
> http://mail.zope.org/mailman/listinfo/zope-coders