If I have a module say A.py, wherein
import xxx
import yyy
class P:
def __init__(self):
pass
p = P()
Will the last line of code be executed every time I import A, in every module, or just once? I am attempting to make it a singleton instance, i.e. to be able to use only one instance throughout the session of execution. So please share, how that can be done. Thanks.
2 Answers 2
The code at a module's top level is only executed once per process (the first time the module is imported for this process). The module object instance is then stored in sys.modules and subsequent imports will access it from there.
The only caveat is when the same module is imported via 2 different qualified names, in which case it's treated as two distinct modules (hence the top-level is executed twice for the same process), but that's really a quite uncommon corner case.
Here's a simple example where you can see that in actions - mod.py is imported four time but executed only once (on the first import):
bruno@bigb:~/Work/playground/imptrace$ ls *.py
a.py b.py c.py main.py mod.py
bruno@bigb:~/Work/playground/imptrace$ cat mod.py
class P(object):
def __init__(self):
print "p %s initialzed" % id(self)
p = P()
bruno@bigb:~/Work/playground/imptrace$ cat a.py
print "in a.py"
import mod
bruno@bigb:~/Work/playground/imptrace$ cat b.py
print "in b.py"
import mod
bruno@bigb:~/Work/playground/imptrace$ cat c.py
print "in c.py"
import mod
bruno@bigb:~/Work/playground/imptrace$ cat main.py
import a
import b
import c
import mod
bruno@bigb:~/Work/playground/imptrace$ python main.py
in a.py
p 139818712152976 initialzed
in b.py
in c.py
Edit: You state that
I am attempting to make it a singleton instance,
This won't make your class a singleton - nothing prevents someone to create other P instances. If you really want a singleton, you'll have to either override P.__new__() to prevent more than on single instance to be created (canonical singleton) or change P so that it only uses class attributes and classmethods, so that all instances will actually share the same attributes.
3 Comments
Yes - you are indeed correct.
Every time you import this class, an object of type P will be created.
Everything outside the class/function definition is effectively seen as an executable command
printto convince yourself :)