Monkeypatching an object to become callable

Nikolaus Rath Nikolaus at rath.org
Wed Aug 12 01:21:16 CEST 2009


Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> writes:
> 7stud a écrit :
> (snip)
>> class Wrapper(object):
>>     def __init__(self, obj, func):
>>         self.obj = obj
>>         self.func = func
>>
>>     def __call__(self, *args):
>>         return self.func(*args)
>>
>>     def __getattr__(self, name):
>>         return object.__getattribute__(self.obj, name)
>
> This should be
>
>           return getattr(self.obj, name)
>
> directly calling object.__getattribute__ might skip redefinition of
> __getattribute__ in self.obj.__class__ or it's mro.

Works nicely, thanks. I came up with the following shorter version which
modifies the object in-place:

class Modifier(obj.__class__):
     def __call__(self):
         return fn()

obj.__class__ = Modifier


To me this seems a bit more elegant (less code, less underscores). Or
are there some cases where the above would fail?


Best,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C



More information about the Python-list mailing list