dinamically altering a function

Steven Bethard steven.bethard at gmail.com
Sat Mar 12 16:48:23 EST 2005


vegetax wrote:
> I i need a decorator that adds a local variable in the function it
> decorates, probably related with nested scopes, for example:
> 
> def dec(func):
>     def wrapper(obj = None):
>         if not obj : obj = Obj()
>   <bind obj to func>
>  return func()
> 
>     return wrapper()
> 
> @dec()
> def fun(b):
>     obj.desc = 'marked'
>     obj.b = b
>     return obj
> 
> so the call to fun : fun(obj = myobj,'b argument')
> or fun('b argument')
> 
> So the function "fun" assumes it has an obj instance and other instance
> objects computed by the decorator, this decorator will be like a generic
> factory for this kind of functions,which depends on the decorator to work.

For a byte-code hack that does something similar, see the recent thread:

http://mail.python.org/pipermail/python-list/2005-March/270324.html

It can do something like:

py> class Object(object):
...     pass
...
py> @presets.presets(obj=Object())
... def fun(b):
...     obj.desc = "marked"
...     obj.b = b
...     return obj
...
py> fun(1)
<__main__.Object object at 0x01162BD0>
py> fun(1).b
1

But note that you then only have a single instance for all calls to the 
function:

py> fun(1) is fun(2)
True

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?

STeVe



More information about the Python-list mailing list