Recently I noticed that using modules was a good option to keep my python programming tidy. For getting started, I made one module (named, oop.py) with a single class in it, which looks like below:
#Module named oop
class Team:
def __init__(self):
print "class Team initialized"
def displayTeam(self):
print "Team name: ", self.name, ",Rank :" , self.rank
def setTeam(self,name,rank):
self.name = name
self.rank = rank
t1 = Team()
t1.setTeam("Man-Utd", 1)
t1.displayTeam()
According to python documentation, if we want to use specific attribute from a module then we use <from module_name> import <attribute>
. I wanted to only load the "class Team"
In another python code (named, oop1.py) I simply imported the above module. oop.py is as mentioned below :
#This is oop1.py.
#Importing module oop
from oop import Team
The output of python oop1.py
from terminal was :
class Team initialized
Team name: Man-Utd ,Rank : 1
By declaring from oop import Team
, I was expecting to load only class definition. Why are those extra lines t1 = Team()
t1.setTeam("Man-Utd", 1)
t1.displayTeam()
from oop.py are getting executed ?
Is initialization not allowed in modules ? What should I do if I only want class Team structure and not other stuff of module ? Corerct me if I am wrong somewhere.
In python modules are objects. In order to create a module object the code that it contains is executed and the bindings that are found are added to the object as attributes.
Specifying what you want to import doesn't change the fact that the whole module is executed and afterwards only that single binding is put in the scope by the import
.
It's standard practice to put any code that you do not want to execute when importing after a guard:
if __name__ == '__main__':
# your code here
__name__
is a special global that is __main__
only when executing the module. During an import it is set to the name of the module (and thus that code wont be executed).
To learn more about modules read the documentation. There is also a section that explains the above mentioned guard: Executing modules as scripts
Yes, the code of every module you import will be run on the initial import
. (Since Python is an interpreted language, that's expected behavior.)
If there are parts of the module that you don't want run on imports, only when the file is run directly, do
if __name__ == "__main__":
t1 = Team()
t1.setTeam("Man-Utd", 1)
t1.displayTeam()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With