Decorator to mark a method to be executed no more than once even if called several times
class, decorator, methods, python
Solution
import functools
def execonce(f):
@functools.wraps(f)
def donothing(*a, **k):
pass
@functools.wraps(f)
def doit(self, *a, **k):
try:
return f(self, *a, **k)
finally:
setattr(self, f.__name__, donothing)
return doit
Problem
I will go straight to the example: ``` class Foo: @execonce def initialize(self): print 'Called' >>> f1 = Foo() >>> f1.initialize() Called >>> f1.initialize() >>> f2 = Foo() >>> f2.initialize() Called >>> f2.initialize() >>> ``` I tried to define `execonce` but could not write one that works with methods. PS: I cannot define the code in `__init__` for `initialize` has to be called sometime after the object is initialized. cf - cmdln issue 13