Singleton implementation problems

Terry Reedy tjreedy at udel.edu
Fri Jul 4 10:37:04 CEST 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.

Peter is correct that a module can only be imported once per *name*.
In 3.0b1
temp.py
=================
print(__name__)
import temp
print(__name__)
from sys import modules as m
print(m['__main__'] is m['temp'])

produces
==================
__main__
temp
temp
False
__main__
False

Duplicate imports under multiple names are a known problem, and this is 
not the only way to create such.  But what can an interpreter do when it 
sees 'import x' other than check that 'x' is not already a key in 
sys.modules?  Iterate through sys.modules (increasingly slow as the dict 
grows) and do what exactly?  The semantics of 'import x' are to get 
sys.modules['x'] if it exists; otherwise 'initialize' module x according 
to what that means for the implementation and current state and mode of 
operation of the system.  Modules are not required to have .__file__ 
attributes since they do not have to come from named files ;-).  (And 
then the module is bound to 'x' in the importing namespace.)

Terry Jan Reedy




More information about the Python-list mailing list