Classes and modules are singletons?

Terry Reedy tjreedy at udel.edu
Wed Mar 5 21:05:31 EST 2008


"Steven D'Aprano" <steve at REMOVE-THIS-cybersource.com.au> wrote in message 
news:13suj3u2d17f205 at corp.supernews.com...
|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.

If I understand your question, classes are not singletons:
>>> ll=[]
>>> for i in range(2):
 import string
 ll[i]=string

>>> ll[0] is ll[1]
True
>>> for i in range(2):
 class C: pass
 ll[i] = C


>>> ll[0] is ll[1]
False

tjr






More information about the Python-list mailing list