Singleton implementation problems

Peter Otten __peter__ at web.de
Fri Jul 4 04:33:20 EDT 2008


Ben Finney wrote:

> Peter Otten <__peter__ at web.de> writes:
> 
>> The problem is the structure of your program. The myset module is
>> imported twice by Python, once as "myset" and once as "__main__".
> 
> Yes, this is the problem. Each module imports the other.
> 
>> Therefore you get two distinct MySet classes, and consequently two
>> distinct MySet.__instance class attributes.
> 
> Are you sure? This goes against my understanding: that 'import foo'
> will not re-import a module that's already been imported, but will
> instead simply return the existing module.

The main script is put into the sys.modules cache as "__main__", not under
the script's name. Therefore the cache lookup fails.
 
> So, I think if one evaluated 'myset is __main__', you'd find they are
> exactly the same module under different names; and therefore that
> there is only *one* instance of 'MySet', again under two names.

No:

$ cat tmp.py
import tmp
import __main__

print tmp is __main__

$ python tmp.py
False
False

Peter



More information about the Python-list mailing list