Classes and modules are singletons?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Wed Mar 5 21:31:58 EST 2008
On Wed, 05 Mar 2008 21:05:31 -0500, Terry Reedy wrote:
> If I understand your question, classes are not singletons:
>>>> ll=[]
>>>> for i in range(2):
> import string
> ll[i]=string
Where's the IndexError? :-)
>>>> ll[0] is ll[1]
> True
But yes, modules are singletons in that way, at least if you go through
the import mechanism.
>>>> for i in range(2):
> class C: pass
> ll[i] = C
>
>
>>>> ll[0] is ll[1]
> False
Ah, but each time around the loop you create a *new class* that just
happens to be called C. An alternative way to see similar behaviour is:
def foo(x=None):
class C(object):
X = x
return C
Naturally foo() is foo() gives False -- although both classes are called
C, they are different classes that just happen to have the same state.
I accept my question about classes being singletons is not well-formed,
not even in my own mind. I guess one way of asking is, for any two class
objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"?
--
Steven
More information about the Python-list
mailing list