First time initialization

Oct 24, 2015 20:26


They say a good FORTRAN programmer will program FORTRAN in any language. Here’s a style of lazy or first time initialization that would work in C++, Java and Python… Only in Python one can do better.

>>> class A(object):
def __init__(self):
self.is_initialized = False
def foo(self):
print 'foo'
def bar(self):
print 'is initialized?'
if not self.is_initialized:
print 'initializing...'
self.is_initialized = True
self.foo()
>>> o = A()
>>> o.bar()
is initialized?
initialiing...
foo
>>> o.bar()
is initialized?
foo
>>> o.bar()
is initialized?
foo

The code for bar is somewhat chatty. If we forget about that, all a client needs to know is that bar "does foo". The fact that the first call is special (initialization logic) is an implementation detail. Looking at it as a programmer who wrote the class, it is also as good as it gets. Initialization is only done the first time. Still the fact that we check self.is_initialized every time is lame. Performance is not an issue obviously, it just feels unnecessary. So here's something we could not do in a "less dynamic" language:

>>> class B(object):
def foo(self):
print 'foo'
def bar(self):
print 'initializing...'
self.foo()
print 'call foo right away from now on'
self.bar = self.foo
>>> o = B()
>>> o.bar()
initialiing...
foo
call foo right away from now on
>>> o.bar()
foo
>>> o.bar()
foo
>>>

As an extra bonus bar logic is now quite linear: we know for sure it will only be called one time so there is no condition to check.

python

Previous post Next post
Up