python_wiki:if_name_main

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python_wiki:if_name_main [2016/11/30 22:00]
billdozor [if __name__ main]
python_wiki:if_name_main [2019/05/25 23:50]
Line 1: Line 1:
-====== if __name__ main ====== 
  
-**General Information** 
- 
-Many python source files will have an interesting if statement around main(). This is why it exists. 
- 
-**Checklist** 
-  * Python versions: 2 and 3 
- 
----- 
- 
-===== The Code ===== 
- 
-<code python> 
-if __name__ == '__main__': 
-  main() 
-</code> 
- 
-==== Explanation ==== 
- 
-It may include other statements as well. 
- 
-This special if statement is checked by the python interpreter itself when it reads the source file. 
- 
-  * If the source is being run as the main program, it sets that source file as the special "__name__" variable to "__main__". 
-  * If the source file is being imported from another module, the "__name__" variable will be set to the module's name instead. 
- 
-The entire reason behind this is: 
-  * Sometimes modules are written to be executed directly. 
-  * They could also be imported for use in another module. 
-  * The main check allows for only the "main" code to execute if run directly and not if someone imports the module to call functions. 
  • python_wiki/if_name_main.txt
  • Last modified: 2019/05/25 23:50
  • (external edit)