accessors and lazy initialization

Bill foobarbazqux at ftml.net
Fri Mar 10 18:43:03 CET 2006


Hello --

I'm a Java programmer who's slowly getting up to speed in Python.  In
general I try to initialize the state of my objects as late as
possible, in the accessor.  So if I have a member "_foo", my accessor
is something like:

public FooType getFoo() {
    if (_foo == null) {
        // initialize _foo here
    }
    return _foo;
}

I'd like to do lazy initialization in Python as well:

def getFoo():
    try:
        return _foo
    except AttributeError:
        # initialize _foo here
    return _foo

This seems a little clunky.  Is there a more Pythonic way of looking at
this?

Thanks -- Bill.




More information about the Python-list mailing list