Why does simply importing a python module executes everything present in that module ?
Question: 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.


Answer: 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](https://docs.python.org/2/tutorial/modules.html#modules).
There is also a section that explains the above mentioned guard: [Executing
modules as scripts](https://docs.python.org/2/tutorial/modules.html#executing-
modules-as-scripts)

