How to initialize a class variable once

alex23 wuwei23 at
Tue Dec 9 05:39:34 CET 2008

On Dec 9, 2:08 pm, Roy Smith <r... at> wrote:
> I've got a class with a class variable:
> class Foo:
>    _map = {}
> How do I make sure this only gets initialized the *first* time the
> module containing the class is imported?  What appears to be happening
> as it stands is each time the module gets imported, Foo._map get re-
> initialized.

What you're asking for is actually the default behaviour. The Foo
class should only be created once, on the first import, and all
subsequent imports should refer to it:
    class Foo:
        _map = {}
    from foo import Foo
    Foo._map['a'] = 1
    from foo import Foo
    print Foo._map
    import a
    import b

This outputs "{'a': 1}", as expected. The Foo._map that prints is
the same Foo._map that has modified.

You might need to provide some more details about your code.

More information about the Python-list mailing list