Via dilip’s comment, I discovered that Sjoerd Visscher had written a javascript version of my ExecuteOnce program. He had an ingenious solution that avoided the need for the temporary boolean sentinel, as well as the shadow method. So in the spirit of sharing, I’ve updated my code to reflect his technique:
class ExecuteOnce(type):
def donothing(): pass
def sentinel(name, method):
def _method(self, *arg1, **argd):
result = method(self, *arg1, **argd)
setattr(self, name, ExecuteOnce.donothing)
return result
return _method
sentinel = staticmethod(sentinel)
donothing = staticmethod(donothing)
def __new__(cls, classname, bases, classdict):
for name, item in classdict.items():
if callable(item):
classdict[name] = ExecuteOnce.sentinel(name, item)
return type.__new__(cls, classname, bases, classdict)
class Test(object):
__metaclass__ = ExecuteOnce
def method1(self):
print "In method1"
t = Test()
t.method1()
t.method1()
t.method1()
Also, he also taught me one extremely powerful aspect of closures - anonymous storage. The method parameter passed to the sentinel method is really a function object which is stored within the body of the closure - hence the term he uses: “anonymous storage”. It neatly avoids polluting the attribute space of the class, as well as eliminating the possibility of namespace collisions.
And the program is also now much shorter and easier to read. There’s just so much to love about Python!
2 archived reader comments
jonx (2004-09-27)
I’m pretty sure you know this one, but to be really sure here it is: http://ironpython.com/ IronPython is a new Python implementation targeting the .NET and Mono platforms. That could reconcile your new passion with the previous one ;)
**** (2004-09-28)
You might want to check out boo, too: http://boo.codehaus.org/