Classes and modules are singletons?

  • Thread starter Steven D'Aprano
  • Start date
S

Steven D'Aprano

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.:
True


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

Terry Reedy

|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:
import string
ll=string
ll[0] is ll[1] True
for i in range(2):
class C: pass
ll = C

False

tjr
 
S

Steven D'Aprano

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


Where's the IndexError? :)

But yes, modules are singletons in that way, at least if you go through
the import mechanism.

class C: pass
ll = C

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"?
 
M

Micah Cowan

Steven D'Aprano said:
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?


It's not an absolute strict guarantee; it's just implied by the fact
that "import" uses any appropriate objects already found in
sys.modules.
import sys
ll = []
for i in range(2):
.... import string
.... ll.append(string)
.... del sys.modules['string']
....
False

(I'm sure there are very good reasons never to do what I just did there.)
 
C

castironpi

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


Where's the IndexError? :)

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 = 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"?

... def __eq__( self, other ):
... return random.choice([ True, False ])
...... pass
...
You made me think of this. What relevance it has is open to
debate. ...In a separate thread.

http://en.wikipedia.org/wiki/Relevance

It's my Signal-channel signal signal.
 
C

castironpi

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

Where's the IndexError? :)
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"?



Similarly, no.
... def __eq__( self, other ):
... return True
...... pass
...... pass
...False

+1 raised eyebrow
 
C

castironpi

If I understand your question, classes are not singletons:
ll=[]
for i in range(2):
 import string
 ll=string
Where's the IndexError? :)
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"?


Similarly, no.

...     def __eq__( self, other ):
...             return True
...>>> class C( metaclass= metaC ):

...     pass
...>>> class D( metaclass= metaC ):

...     pass
...>>> C==D
True
False

+1 raised eyebrow


Well, you're not going to believe me, but a <scaryword>"bar"</
scaryword> just had an idea.

Don't forget:
class C( metaclass= metaC )
class metaC( metaclass= metametaC )
class metametaC( type ): bor hor hor.

Now for the academics, is it telling a joke? If so, that's pretty
fine--- but.
 
C

castironpi

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"?

C and D are instances of metaC in that.

class metaC( type ):
def what( self ):
return self

class C( metaclass= metaC ): pass
class D( metaclass= metaC ): pass

assert C is C.what() and D is D.what()
#print( C.what(), D.what() )

C= metaC('C',(),{})
D= metaC('D',(),{})
assert C is C.what() and D is D.what()
#print( C.what(), D.what() )

furthermore.
 
C

Carl Banks

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.


Probably because "singleton" is the wrong word. A singleton means
there is one instance of a type; classes are instances of "type" which
can have many instances so classes are not singletons.

Anyway, the answer to what you are probably asking is No. Try this:


For that matter, try this:


Carl Banks
 
C

castironpi

Probably because "singleton" is the wrong word.  A singleton means
there is one instance of a type; classes are instances of "type" which
can have many instances so classes are not singletons.

Anyway, the answer to what you are probably asking is No.  Try this:

What about

?
 
A

Aahz

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"?

Even that stricture fails under the presence of metaclasses. ;-) But
answering your real question, I don't remember off-hand the required
sequence, but it is possible to import a class two different ways such
that the classes are not the object. This can cause problems with e.g.
pickle. Within a single module, given a class defined only once within
that module, the class will be a singleton.
 
C

castironpi

Even that stricture fails under the presence of metaclasses.  ;-)  But
answering your real question, I don't remember off-hand the required
sequence, but it is possible to import a class two different ways such
that the classes are not the object.  This can cause problems with e.g.
pickle.  Within a single module, given a class defined only once within
that module, the class will be a singleton.
--
Aahz ([email protected])           <*>        http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of    
indirection."  --Butler Lampson

I'd like to question the source of the definition of C.__eq__.

Observation:
False

What is different about them? I've created two empty classes, nothing
more.
 
G

Gabriel Genellina

I'd like to question the source of the definition of C.__eq__.

Observation:

False

What is different about them? I've created two empty classes, nothing
more.

Their __name__ attribute?
Types are compared by their memory addresses, not by contents, and that's
enough and efficient for most people. If you require something different,
use a metaclass.
 
S

Steven D'Aprano

Probably because "singleton" is the wrong word. A singleton means there
is one instance of a type; classes are instances of "type" which can
have many instances so classes are not singletons.

Right. I knew there was something funny about using the term "singleton"
to refer to classes, but I couldn't put my finger on it.

[snip]
For that matter, try this:

That example is cheating because you rebind the *name* module.Someclass.
Of course you get something different.

But in any case, I'm satisfied now... the name singleton is inappropriate
for modules and classes, although they are both singleton-like. I like
Gabriel's term "named singleton" (from another thread).

Thank you to everybody who answered.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top