init-once class 'static' data

Fredrik Lundh fredrik at effbot.org
Thu Jan 11 11:11:40 EST 2001


George Young wrote:
> I seem to often need a class to initialize a piece of it's data
> the first time that class is instantiated.  Examples might be a database
> connection, a loading a pixmap, loading and parsing a datafile which
> data will normally be accessed as a directory member of the class...
>
> I'd rather the data not initialize on module load, because in some cases
> the data may never be used.
>
> I've been using an idiom I copied once from someone, but it seems
> pretty kludgy, I'm hoping someone will point out a better way:
>
> class foo:
>    data = None
>    def __init__(self, data=data):
>        if data:
>            self.data = data
>        else:
>            self.data = (some expensive operation)

Does that really work?

Here's a more pydiomatic (imho, at least) solution:

class Foo:

    # class attribute, shared by all instances
    data = None

    def __init__(self):

        if not self.data:
            # set the *class* attribute
            Foo.data = (some expensive operation)

        # now you can use self.data as usual

Hope this helps!

Cheers /F





More information about the Python-list mailing list