0%

Module's Name in Python

Usage for if "__name__" == "__main__":

If the module we import, in addition to defined functions, still has executable code. Then python interpreter would execute this code which is unexpected. Therefore, if we write executable code in modules, better put this code in if "__name__" == "__main__": so that the code under “if” condition won’t be executed unless to execute its module directly. Since only the name of the module to be executed directly is "__main__".

model3.py

1
2
3
4
5
6
7
8
9
10
11
12
13
def foo():
pass

def bar():
pass

# __name__ is a hidden variable in Python which stands for the name of the module
# only the name of the module to be executed directly is "__main__".
if __name__ == '__main__':
print('call foo()')
foo()
print('call bar()')
bar()

test.py

1
2
# When import module3, the code under if condition in module3 won't be executed since its name is module3 rather than "__main__"
import module3