![](https://secure.gravatar.com/avatar/d91ce240d2445584e295b5406d12df70.jpg?s=120&d=mm&r=g)
Nick Coghlan wrote:
[ much good, including the @instance decorator ]
P.S. If all you want is somewhere to store mutable state between invocations, you can always use the function's own attribute space
>>> def f(): print "Hi world from %s!" % f >>> f() Hi world from <function f at 0x00AE90B0>! Not really. That assumes the expected name is (permanently) bound to *this* function in this function's globals. That's normally true, but not always, so relying on it seems wrong. >>> f="a string" >>> g() Hi world from a string! And of course, sometimes I really do want shared state, or helpers (like other methods on a class), or one-time ininitialization plus per-call parameters (like the send method on 2.5 generators), or ... -jJ
![](https://secure.gravatar.com/avatar/f3ba3ecffd20251d73749afbfa636786.jpg?s=120&d=mm&r=g)
Jim Jewett wrote:
Nick Coghlan wrote:
[ much good, including the @instance decorator ]
P.S. If all you want is somewhere to store mutable state between invocations, you can always use the function's own attribute space
>>> def f(): print "Hi world from %s!" % f
>>> f() Hi world from <function f at 0x00AE90B0>!
Not really. That assumes the expected name is (permanently) bound to *this* function in this function's globals. That's normally true, but not always, so relying on it seems wrong.
Well, true. If you want it to be bullet-proof, you have to use a closure instead:
def make_f(): ... def f(): ... print "Hi world from %s!" % f ... return f ... f = make_f() f() Hi world from <function f at 0x00AE90B0>!
The point about the decorators still holds - they stay with the function they're decorating (the inner one), and you don't need to make any of the changes needed in order to decorate the class instead. The above is also a use case for a *function* decorator I've occasionally wanted - an @result decorator, that is the equivalent of the @instance decorator I suggested for classes:
def result(f): ... return f() ... @result ... def f(): ... def f(): ... print "Hi world from %s!" % f ... return f ... f() Hi world from <function f at 0x00AE90B0>!
I never actually did it, though, as I was stuck on Python 2.2 at the time. This is something of a tangent to the real discussion though, so I'll leave this one there :) Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia --------------------------------------------------------------- http://www.boredomandlaziness.org
participants (2)
-
Jim Jewett
-
Nick Coghlan