Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does simply importing a python module executes everything present in that module ? [duplicate]

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.

like image 898
v1h5 Avatar asked Dec 19 '22 13:12

v1h5


2 Answers

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

like image 132
Bakuriu Avatar answered Feb 22 '23 22:02

Bakuriu


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()
like image 44
Tim Pietzcker Avatar answered Feb 23 '23 00:02

Tim Pietzcker