Basic Python

Module, __name__, __main__

Naranjito 2021. 4. 27. 11:34
  • 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/