Per instance descriptors ?

Steven Bethard steven.bethard at gmail.com
Thu Mar 23 13:15:00 EST 2006


bruno at modulix wrote:
> Using a class as a
> decorator, I have of course only one instance of it per function - and
> for some attributes, I need an  instance per function call.

Per function call?  And you want the attributes on the function, not the 
result of calling the function?  If so, that'd be pretty difficult...

I guess you could do something like:

 >>> class FuncWrapper(object):
...     def __init__(self, func):
...         self.func = func
...         self.call_no = 0
...         self.get_foo = lambda: 'one thing'
...     def __call__(self, *args, **kwargs):
...         self.call_no += 1
...         if self.call_no == 1:
...             del self.get_foo
...             self.get_bar = lambda: 'another thing'
...         else:
...             del self.get_bar
...             self.get_baz = lambda: 'a third thing'
...         return self.func(*args, **kwargs)
...
 >>> @FuncWrapper
... def f(*args, **kwargs):
...     print args, kwargs
...
 >>> f.get_foo()
'one thing'
 >>> f('test 1')
('test 1',) {}
 >>> f.get_foo
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'FuncWrapper' object has no attribute 'get_foo'
 >>> f.get_bar()
'another thing'
 >>> f(test=2)
() {'test': 2}
 >>> f.get_bar
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'FuncWrapper' object has no attribute 'get_bar'
 >>> f.get_baz()
'a third thing'

But that looks pretty nasty to me.  It sounds like your architecture 
could use some redesigning -- having different attributes on a function 
for each function call seems like a bad idea.  Can't you have the 
returned objects carry the different attributes?

STeVe



More information about the Python-list mailing list