ʻIf name == "main": ` One line that often appears in Python source code is You can get rid of it with "magic" What is it useful for?
For example, suppose you create a file called helloWorld.py
.
helloWorld.py
def main():
print("Hello Python!")
#Main
main()
Earlier ʻIf name == There is no description of "main" `
$ python helloWorld.py
Hello Python!
The execution result is obtained. However, in this configuration, even if ʻimport` is done
>>> import helloWorld #At this point, "Hello Python!Is displayed
Hello Python!
So, I don't want to just import a Python file and try to reuse the main function, but the execution is selfish. Therefore
def main():
print("Hello Python!")
# main()Insert one line before
if __name__ == "__main__":
main()
The inside of this if statement is not executed when it is imported.
>>> import helloWorld
>>>
--If you do import hello World:
ʻIf name == In the variable nameof "__main__" Contains the module name of this Python file as a string. In other words The content of
name is the string" helloWorld "`
It has become.
--If you run the program like python helloWorld.py:
Inside helloWorld.py
The __name__ variable is the string" __main__ "
Will be.
Inside helloWorld.py
, which was ʻimport helloWorld, The string will be
name ==
"helloWorld" `.
Inside the helloWorld.py
that was python hello.py
The string is __name__
== " __main__ "
.
Therefore, it is possible to prevent it from moving without permission just by ʻimport`! That's why. Well, Python is deep. There is a lot of room for learning.
Recommended Posts