How to initialize a class variable once

Roy Smith roy at panix.com
Tue Dec 9 19:58:18 EST 2008


In article <mailman.5289.1228837023.3487.python-list at python.org>,
 Joe Strout <joe at strout.net> wrote:

> On Dec 9, 2008, at 4:31 AM, Brian Allen Vanderburg II wrote:
> 
> > There is one situation where a module can be imported/executed  
> > twice, if it is the __main__ module.

> Anyway, thanks for pointing this out; I bet it's the root cause of the  
> OP's observation.

Wow, good diagnosis!  This was happening in a test framework (using 
unittest).  I had a class which had a @staticmethod factory function, and a 
class member dict where __init__() registered every instance of the class 
that got created.  

Something was going wrong, so in my test code (i.e. in __main__), I 
imported the module directly and printed the dict.  Lo and behold, it was 
empty!  As far as I could tell,

class Foo:
   _map = {}

was getting executed again, which made no sense.  I even went as far as 
printing out id(Foo) in both places to make sure I really had the same 
class (I did).

Thanks for the help.  I never would have figured this out on my own.



More information about the Python-list mailing list