
Am 06.06.2010 14:30, schrieb George Sakkis:
It would be nice if setattr() was extended to allow usage as a decorator:
class Foo(object): pass
@setattr(Foo) def bar(self): print 'bar'
@setattr(Foo, 'baz') def get_baz(self): print 'baz'
Foo().bar() bar Foo().baz() baz
Here's a pure Python implementation:
_setattr = setattr def setattr(obj, *args): if len(args) >= 2: return _setattr(obj, *args) return lambda f: _setattr(obj, args[0] if args else f.__name__, f) or f
Thoughts ?
Since this is useful for functions only, I would not try to overload a simple builtin, call it def_on() and put it in my utility module: @def_on(Foo) def method(self): pass Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out.