How to initialize a class variable once

Benjamin Kaplan benjamin.kaplan at case.edu
Tue Dec 9 00:04:32 EST 2008


On Mon, Dec 8, 2008 at 11:44 PM, John Machin <sjmachin at lexicon.net> wrote:

> On Dec 9, 3:36 pm, Matimus <mccre... at gmail.com> wrote:
> > On Dec 8, 8:08 pm, Roy Smith <r... at panix.com> 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.
> >
> > Unless you are calling reload() on the module, it will only ever get
> > _loaded_ once. Each additional import will just yield the existing
> > module. Perhaps if you post an example of the behavior that leads you
> > to believe that the class variables are getting reinitialized
>
> and change it to
>   class Foo(object):
> because we care little about old-style classes these days


unless the OP is using Python 3 in which case that would be redundant. This
is going to be really confusing unless every poster lists their python
version.



>
> and put a print statement in the module just before the class
> statement and print statements before and after each import statement
> so that we can see what is happening.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081209/65302453/attachment-0001.html>


More information about the Python-list mailing list