Fatemeh Sangin
Fatemeh Sangin

Reputation: 551

Why do you run other lines of codes of a python file(say test.py) when you are just importing a piece of test.py from somewhere else (say main.py)?

I have two python files. One is main.py which I execute. The other is test.py, from which I import a class in main.py. Here is the sample code for main.py:

from test import Test
if __name__ == '__main__':
    print("You're inside main.py")
    test_object = Test()

And, here is the sample code for test.py:

class Test:
    def __init__(self):
        print("you're initializing the class.")
if __name__ == '__main__':
    print('You executed test.py')
else:
    print('You executed main.py')

Finally, here's the output, when you execute main.py:

You executed main.py
You're inside main.py
you're initializing the class.

From the order of outputs above, you can see that once you import a piece of a file, the whole file gets executed immediately. I am wondering why? what's the logic behind that? I am coming from java language, where all files included a single class with the same name. I am just confused that why python behaves this way.

Any explanation would be appricated.

Upvotes: 4

Views: 406

Answers (2)

Olav Aga
Olav Aga

Reputation: 143

What is happening?

When you import the test-module, the interpreter runs through it, executing line by line. Since the if __name__ == '__main__' evaluates as false, it executes the else-clause. After this it continues beyond the from test import Test in main.py.

Why does python execute the imported file?

Python is an interpreted language. Being interpreted means that the program being read and evaluated one line at the time. Going through the imported module, the interpreter needs to evaluate each line, as it has no way to discern which lines are useful to the module or not. For instance, a module could have variables that need to be initialized.

Python is designed to support multiple paradigms. This behavior is used in some of the paradigms python supports, such as procedural programming.

Execution allows the designer of that module to account for different use cases. The module could be imported or run as a script. To accommodate this, some functions, classes or methods may need to be redefined. As an example, a script could output non-critical errors to the terminal, while an imported module to a log-file.

Why specify what to import?

Lets say you are importing two modules, both with a Test-class. If everything from those modules is imported, only one version of the Test-class can exist in our program. We can resolve this issue using different syntax.

import package1
import package2

package1.Test()
packade2.Test()

Alternatively, you can rename them with the as-keyword.

from package1 import Test
from package2 import Test as OtherTest

Test()
OtherTest()

Dumping everything into the global namepace (i.e from test import *) pollutes the namespace of your program with a lot of definitions you might not need and unintentionally overwrite/use.

Upvotes: 2

Daweo
Daweo

Reputation: 36340

where all files included a single class with the same name

There is not such requirement imposed in python, you can put multiple classes, functions, values in single .py file for example

class OneClass:
    pass
class AnotherClass:
    pass
def add(x,y):
    return x+y
def diff(x,y):
    return x-y
pi = 22/7

is legal python file.

According to interview with python's creator modules mechanism in python was influenced by Modula-2 and Modula-3 languages. So maybe right question is why creators of said languages elected to implement modules that way?

Upvotes: 1

Related Questions