[Introduction to Python] What is the important "if __name__ =='__main__':" when dealing with modules?

Reference site: [Introduction to Python] What is the important "if name =='main':" when dealing with modules?

[Introduction to Python] What is the important "if name =='main':" when dealing with modules?

When I'm studying Python and looking at sample programs, I often see the sentence "if name =='main':". Main is indispensable for writing programs in other programming languages such as C and Java, but in Python, main is not usually used when coding.

However, this sentence plays an important role in working with modules in Python. This time, I will explain what this "if name =='main':" means.

What is a module?

Python code can be saved as a script file and reused by other programs. That file is called a module. "Import" is used when loading the standard library in Python, but by loading your own module using import, you can use the functions and classes defined in that module in other programs as well.

if name == ‘main’: meaning

What is name__?

Now that you know what the module means, let's talk about the variable "name". As an example, suppose you have the following program test.py.

test.py
def test():
    print('Hello World!')
    
if __name__ == '__main__':
    test()

The result of executing this program is as follows.

Hello World!

In this example, we just defined a function called test that displays "Hello World!". I haven't declared the variable "name" anywhere. Nevertheless, the fact that test () is being executed means that the if statement is returning True. What exactly does that mean?

Let's first look at this variable called "name". In fact, this variable name is created automatically when you load a Python script on a Python printer. In addition, the module name of the script being executed is automatically assigned to it.

if name == ‘main’: meaning

I found that a variable called name was created automatically, and the module name of the script being executed was automatically assigned. However, I don't remember making a module called main. Where does this main come from?

In fact, when you run a Python script directly, the script file will be recognized as a module named "main". Therefore, if you execute the script file directly, the value main will be automatically assigned to the name variable.

In other words, the meaning of "if name =='main':" was "execute only if it is executed directly, not execute otherwise". In the previous example, we ran test.py directly, so the if statement returned True and test () was ran.

As a test, I added a process to display the executed module name in test.py.

def test():
    print('Hello World!')
    
if __name__ == '__main__':
    test()
    
print('Module name:{}'.format(__name__))  #Display the name of the executed module

If you do this, you will get the following results:

Hello World! Module name: main

When you execute the script file directly, you can see that the module name is "main".

So what does "except when run directly" mean? That is when I read this script file as a module from another program. I created test2.py which imports test.py as a module.

test2.py
import test  #test.Import py

Execution result

Module name: test

If you import and run test.py, you will see that the module name is "test". That is, test.py is running as a test module, so name is assigned "test". Therefore, "if name =='main':" returns False, so test () was not executed.

"If name =='main':" is used for testing while creating a module, or when you do not intend to modularize at the moment but want to avoid unnecessary processing when modularizing. You may not think about modularization or reuse while you are making a program by yourself, but it is an essential idea when you make a large-scale program. Let's remember it.

Recommended Posts

[Introduction to Python] What is the important "if __name__ =='__main__':" when dealing with modules?
[Introduction to Python] What is the method of repeating with the continue statement?
[Introduction to Python] What is the most powerful programming language now?
What to do when the value type is ambiguous in Python?
[Introduction to Python] What is the difference between a list and a tuple?
What to do if the server doesn't start with python manage.py runserver
[What is an algorithm? Introduction to Search Algorithm] ~ Python ~
Introduction to Python with Atom (on the way)
[Introduction to Udemy Python 3 + Application] 54. What is Docstrings?
What to do if you get a "Wrong Python Platform" warning when using Python with the NetBeans IDE
What to do if you get an error when installing python with pyenv
[Introduction to Python] How to iterate with the range function?
[Python] What to do when No module named'pyproj.datadir' appears when Exe is done with PyInstaller
[Introduction to Python] What is the recommended way to install pip, a package management system?
What to do if the progress bar is not displayed in tqdm of python
Python "if __name__ == ‘__main__’: ”means
[Python] if __name__ == What is'__main__' :?
I want to initialize if the value is empty (python)
What I did to welcome the Python2 EOL with confidence
Try to decipher the garbled attachment file name with Python
[Introduction to Python] How to get data with the listdir function
[Python] What is a with statement?
How to not escape Japanese when dealing with json in python
[Introduction to Python] How to split a character string with the split function
[Python] What is @? (About the decorator)
How to deal with the problem that the current directory moves when Python is executed from Atom
[python] What is the sorted key?
[Python] What is pip? Explain the command list and how to use it with actual examples
What to do with PYTHON release?
What to do if Insecure Platform Warning appears when running Python
What to do if the inode is exhausted on EC2 Linux
What to do when a part of the background image becomes transparent when the transparent image is combined with Pillow
What is the python underscore (_) for?
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
How to utilize Python with Jw_cad (Part 1 What is external transformation)
What to do if the user name is changed and the pyenv library path does not pass
[Python] What to do when PEP8 is violated in the process of importing from the directory added to sys.path
How to write what to do when an application is first displayed in Qt for Python with Designer
What skills do I need to program with the FBX SDK Python?
[PostgreSQL] How to grant superuser authority when the user (role) with superuser authority is 0
What to do if there is a decimal in python json .dumps
[Python] What is a formal argument? How to set the initial value
What to do when the result downloaded via scrapy is in English
What to do if the Pipenv environment is corrupted by updating Homebrew
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
What to do if ipython and python start up with different versions
[Introduction to Python] How to sort the contents of a list efficiently with list sort
What to do if the Chainer (Windows) sample mnist terminates with WinError 183.
What to do if an error occurs when importing numpy with VScode
[Introduction to Python] How to write a character string with the format function
What to do when the warning "The environment is in consistent ..." appears in the Anaconda environment
How to automatically notify by phone when the python system is down
What is the fastest way to create a reverse dictionary in python?
[Introduction to Udemy Python3 + Application] 33. if statement
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
[Introduction to Python] Let's use foreach with Python
[Python] Introduction to CNN with Pytorch MNIST
What is "mahjong" in the Python library? ??
When changing the table name with flask_migrate
The road to compiling to Python 3 with Thrift
What to do if you get the error RuntimeError: Python is not installed as a framework when trying to use matplitlib and pylab in Python 3.3