Decorator to mark a method that should be executed no more than once, even if called several times

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 can’t define the code in __init__ for initialize should be called some time after the object is initialized. cf - cmdln 13 problem

+4
source share
3 answers
 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 
+6
source

You can do something like this:

 class Foo: def __init__(self): self.initialize_called = False def initialize(self): if self.initalize_called: return self.initialize_called = True print 'Called' 

It is easy and easy to read. There is another instance variable and some code needed for the __init__ function, but it will satisfy your requirements.

0
source

try something like this

 def foo(): try: foo.called except: print "called" foo.called = True 

methods and functions are objects. You can add methods and attributes to them. This may be useful for your business. If you want a decorator, just ask the decorator to highlight this method, but first check the flag. If the flag is found, the null method is returned and therefore executed.

0
source

All Articles