Why do you add a main ()-if statement in Python?

What is Python name?

ʻ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
>>>

Why the import doesn't run

--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 ofname 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.

Summary

  1. Inside helloWorld.py, which was ʻimport helloWorld, The string will be name == "helloWorld" `.

  2. 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

Why do you add a main ()-if statement in Python?
What to do if you get a minus zero in Python
What happens if you do "import A, B as C" in Python?
If you encounter a "Unicode Decode Error" in Python
[Python version] Why can't you do object-oriented development in Java?
If you write TinderBot in Python, she can do it
Do you need a Python re.compile?
If you want to assign csv export to a variable in python
Check if you can connect to a TCP port in Python
Do a non-recursive Euler Tour in Python
Python / dictionary> setdefault ()> Add if not in dictionary
[Basics of python basics] Why do __name__ == "__main__"
Python if statement
[Python] if statement
What to do if there is a decimal in python json .dumps
If you want a singleton in python, think of the module as a singleton
What to do if you can't use scikit grid search in Python
Python --How do you split a list into evenly sized chunks in Python?
To add a module to python put in Julialang
[Python] What to do if you get a ModuleNotFoundError when importing pandas using Jupyter Notebook in Anaconda
Why you are interested in motor control in Python
What to do if you get a "No versions found" error in pipenv
A solution if you accidentally remove the python interpreter in / usr / local / bin /.
If you guys in the scope kitchen can do it with a margin ~ ♪
What to do if a Unicode Encode Error occurs in Sublime Text Python
What to do if you get "Python not configured." Using PyDev in Eclipse
Python basic if statement
Check if the string is a number in python
% And str.format () in Python. Which one do you use?
BigQuery-If you get a Reason: responseTooLarge error in Python
What to do if a UnicodeDecodeError occurs in pip
Until you insert data into a spreadsheet in Python
A Java programmer studied Python. (for, if, while statement)
When you want to plt.save in a for statement
What to do if you get `No kernel for language python found` in Hydrogen
What to do if you get an error when importing matplotlib in Python (Mac)
Understand Python yield If you put yield in a function, it will change to a generator
What to do if you can't hit the arrow keys in the Python interactive console
What to do if you run python in IntelliJ and end with an error
Take a screenshot in Python
What to do if ʻarguments [0] .scrollIntoView ();` fails in python selenium
Create a function in Python
Create a dictionary in Python
Python "if __name__ == ‘__main__’: ”means
What to do if pip gives a DistributionError in Homebrew
How to import a file anywhere you like in Python
Build a Python development environment in Eclipse (add HTML editor)
[Python] How to write an if statement in one sentence.
How to define multiple variables in a python for statement
What to do if you get "coverage unknown" in Coveralls
Addition with Python if statement
When converting a string (a-> b) in Python, which is faster, if statement or dictionary type?
What to do if a 0xC0000005 error occurs in tf.train.start_queue_runners ()
[Road to intermediate Python] Use if statement in list comprehension
Do something like a Python interpreter in Visual Studio Code
Make a bookmarklet in Python
What to do if you get Swagger-codegen in python and Import Error: No module named
What to do if you can't log in as root
Draw a heart in Python
What to do if you get a Cannot retrieve metalink for repository error in yum
A set of script files that do wordcloud in Python3