Often seen in python scripts,
pseudo.py
if __name__ == '__main__':
I didn't know what it was.
I used this as a reference. http://programming-study.com/technology/python-if-main/
In python, you often pull and use something defined in other scripts. Import the library. It is useful when you want to make a function you defined yourself into a separate script and import it as a module (although it is not possible now).
\ _ \ _ Name \ _ \ _ in the above if is a variable that is automatically created when the script is executed, and when the script is executed directly, \ _ \ _ name \ _ \ _ is \ _ \ _ main \ _ The name \ _ is stored.
In other words, the above if statement branches depending on whether the script was executed directly from the shell.
As shown below, I wrote a script that has executable statements inside and outside the if statement.
name_is_main.py
def func(a,b):
return a + b
print('MY NAME IS ' + __name__)
if __name__ == '__main__':
print('hello!')
print(func(3,4))
Execution result: MY NAME IS __main__ hello! 7
name_is__not_main.py
import name_is_main as nim
print('my name is' + __name__)
if __name__ == '__main__':
print('world!')
print(nim.func(7,8))
Execution result: MY NAME IS name_is_main my name is __main__ world! 15
In name \ _is \ _main.py, \ _ \ _ main \ _ \ _ was entered in \ _ \ _ name \ _ \ _ as it was, and the contents of the if statement were also executed.
In name \ _is \ _ not \ _main.py, the print statement outside the if statement of the imported name \ _is \ _main.py was also executed. In the imported name \ _is \ _main.py, the script name name \ _is \ _main is stored in \ _ \ _ name \ _ \ _. On the other hand, \ _ \ _ main \ _ \ _ was stored in \ _ \ _ name \ _ \ _ of name \ _is \ _ not \ _main.py itself.
As mentioned above, if there is an extra description in the script to be imported, it will be executed without permission on the importing side.
In the site that I referred to, it was introduced to write a script to test the operation of the module as a usage of if \ _ \ _ name \ _ \ _ == \ _ \ _ main \ _ \ _ :. It was. I see.
How is it used outside of testing?
When you're writing a script that you don't intend to modularize, what do you guys do if you get "I think this function can be used elsewhere, so think about modularization ..."? At that point, do you move the function to another script, or do you decide to use an if statement like the one above and leave it in the script as is?
Recommended Posts