dinamically altering a function

Steven Bethard steven.bethard at gmail.com
Sat Mar 12 17:50:11 EST 2005


vegetax wrote:
> Steven Bethard wrote:
>>Have you considered using OO here?  You might find that this is more
>>easily written as:
>>
>>py> class Object(object):
>>...     pass
>>...
>>py> class fun(object):
>>...     def __new__(self, *args):
>>...         if len(args) == 2:
>>...             obj, b = args
>>...         elif len(args) == 1:
>>...             obj, [b] = Object(), args
>>...         else:
>>...             raise TypeError
>>...         obj.desc = "marked"
>>...         obj.b = b
>>...         return obj
>>...
>>py> myobj = Object()
>>py> fun(myobj, 2)
>><__main__.Object object at 0x01162E30>
>>py> myobj.b
>>2
>>py> obj = fun(1)
>>py> obj.b
>>1
>>
>>This doesn't use any bytecode hacks, but I'm still not certain it's
>>really the way to go.  What is it you're trying to write this way?
> 
> OO doesnt work here,i have factored to classes with inheritance but it looks
> clumsy and it is clumsy to use, this things are in nature,functions.
> 
> What i want is to declare in the decorator some code that is common to all
> these functions, so the functions assume that the decorator will be there
> and wont need to duplicate the code provided by it, and the functions are
> not known ahead of time, it has to be dynamic.

If you need to use it as a decorator, you could try something like:

py> class Object(object):
...     pass
...
py> class ObjectSupplier(object):
...     def __init__(self, func):
...         self.func = func
...     def __call__(self, *args):
...         if len(args) == 2:
...             obj, b = args
...         elif len(args) == 1:
...             obj, [b] = Object(), args
...         else:
...             raise TypeError
...         return self.func(obj, b)
...
py> @ObjectSupplier
... def fun(obj, b):
...     obj.desc = "marked"
...     obj.b = b
...     return obj
...
py> fun(1)
<__main__.Object object at 0x01162910>
py> fun(1).b
1
py> myobject = Object()
py> fun(myobject, 2)
<__main__.Object object at 0x01162770>
py> myobject.b
2

Basically, ObjectSupplier just guarantees that the function will be 
called with an initialized Object argument if one isn't supplied.  Note 
that your functions must be declared with the initial argument now though.

STeVe

P.S. Making ObjectSupplier general enough to work with any number of 
arguments is left as an exercise to the reader. ;)



More information about the Python-list mailing list