- Module
It is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
Python interpreter-->Python Files(modules, identified by the .py) ⇡read ⇡sets a few special variable. ⇢ one of those variable is called __name__ ⇡if module runs in the main program : __name__ sets as __main__ ⇡if module importing from another module : __name__ sets as module's name |
1. file_two.py
print("File two __name__ is set to: {}" .format(__name__))
def function_three():
print("Function three is executed")
def function_four():
print("Function four is executed")
if __name__ == "__main__":
print("File two executed when ran directly")
else:
print("File two executed when imported")
1-1. result
File two __name__ is set to: __main__
File two executed when ran directly
2. file_one.py
from file_two import function_three
print("File one __name__ is set to: {}" .format(__name__))
def function_one():
print("Function one is executed")
def function_two():
print("Function two is executed")
if __name__ == "__main__":
print("File one executed when ran directly")
function_two()
function_three()
else:
print("File one executed when imported")
2-1. result
File two __name__ is set to: file_two
File two executed when imported
File one __name__ is set to: __main__
File one executed when ran directly
Function two is executed
Function three is executed
The __name__ variable for all other modules that are being imported will be set to their module's name. (file_two)
reference : www.freecodecamp.org/news/if-name-main-python-example/
'Basic Python' 카테고리의 다른 글
class inheritance (0) | 2021.05.04 |
---|---|
copy, copy.copy, copy.deepcopy, get, next, id (0) | 2021.05.04 |
Class, pass, instance, binding, Object, variable, self, method, __init__, dir, namespace, __dict__, __del__ (0) | 2021.04.20 |
parameter, argument, def, *arg, **kwargs, return, global, *val, nonlocal, namespace (0) | 2021.01.27 |
with as, open, dump, load, contextlib (0) | 2020.12.26 |