Reputation: 19
I wrote 2 python scripts.
first.py one contains two functions like below:
def function1():
'''do somethong'''
def function2():
'''do something'''
print("Outside of the functions in first.py")
I have imported above two functions from first.py to second.py like below:
from first import function1,function2
def function3():
'''do something with func1 & func2'''
print("Outside of the function in second.py")
when i run second.py, it runs whole first.py script even though i have imported funcion1 & function2 alone.
I am getting output like below:
Outside of the functions in first.py
Outside of the function in second.py
why it should print the print statement from first.py which is outside of those two functions? How to avoid it, please help.
Upvotes: 0
Views: 201
Reputation: 963
When you use import
in python even if you use from ... import ...
it runs the entire module, the only difference in the 2 ways of imports is the names which get imported.
in order to ensure that module code which is unnecessary when being imported you wrap it in an if __name__ == '__main__':
block.
__name__
is set by python and it is set to the module name except when executed directly, then it is set to __main__
.
Upvotes: 2