Classes and modules are singletons?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Mar 5 20:44:30 EST 2008


I recall that Python guarantees that module objects are singletons, and 
that this must hold for any implementation, not just CPython: you can 
only ever create one instance of a module via the import mechanism. But 
my google-foo is obviously weak today, I cannot find where the Python 
language reference guarantees that. Can somebody please point me at the 
link making that guarantee?

(Note: you can create multiple modules with the same name and state using 
new.module. I don't think that counts, although it may be a good way to 
win bar bets with your Python buddies.)


But what about classes? Are they singletons? Obviously classes aren't 
Singleton classes, that is, given an arbitrary class C you can create 
multiple instances of C. But what about class objects themselves? I've 
found a few odd references to "classes are singletons", but nothing in 
the language reference.

I've done some experimentation, e.g.:

>>> import module
>>> from module import Class
>>> module.Class is Class
True


but I'm not sure if that's (1) meaningful or (2) implementation-specific.


-- 
Steven



More information about the Python-list mailing list