緯緯道來
緯緯道來

研究所學生,主修資訊工程,熱衷於深度學習與機器學習。初期先以基本的程式教學為主,希望我的文章能夠幫助到你!(https://linktr.ee/johnnyhwu)

What is the use of if __name__ == "__main__" in Python

source: Pixabay

foreword

In Python Module Concept Analysis , we clearly introduced the concept of Module in Python. Before you start reading this article, be sure to understand the concept of Modules in Python!

As we become more and more familiar with the basic syntax of Python, we often introduce modules written by others into our programs, and we start to observe one thing, many people will write in the Module file:

 if __name__ == "__main__":
# code

Why not just write the code directly, but also wrap the code under the judgment of if __name__ == "__main__" :? What's the point of this judgment?

Create a Module (tool.py) and main program (main.py)

First, we also create a Module (tool.py) in Colab, and write the following code in this Module:

 #tool.py

def func1():
print("In func1")

def func2():
print("In func2")

print("in tool.py")

In addition, we add another file (main.py) to Colab as our Main Program and paste the following code:

 # main.py

import tool

tool.func1()
tool.func2()

The result is shown below:

Add a new main.py to Colab


Add tool.py to Colab


Next, we execute the following command in the code block of Colab:

 !python main.py

This instruction means that we execute the Python program main.py through Python's Interpreter. It doesn't matter if you don't know what Python Interpreter is, you just need to know that you are telling the computer to execute this Python program.

After execution, you will get the following results:

 in tool.py
In func1
In func2

I believe that after learning the concept of Python function (Function) , you must be quite clear about why there are outputs of "In func1" and "In func2". However, why is there an output of "in tool.py"? Let's keep reading!

What Python did when it introduced Module

When the main.py program is executed, the first line of code "import tool" is executed:

 # main.py

import tool

tool.func1()
tool.func2()

In a Python program, when the computer is executing the "introduced Module" code, two things actually happen:

  1. The computer will create some special variables for this Module (eg: __name__ )
  2. The computer will execute each line of code in the Module

Taking the above main.py as an example, when we execute main.py, the computer will first execute the line code of "import tool". At this point, some special variables (for example: __name__) will be set for the tool Module, and each line of code in the tool Module will be executed.

When the computer is executing each line of code in the tool Module:

 #tool.py

def func1():
print("In func1")

def func2():
print("In func2")

print("in tool.py")

In addition to defining two Functions, it will also print("in tool.py") at the end.

Now the problem comes, we introduce the tool Module in main.py, but we just want to use the func1( ) and func2( ) defined in the tool Module and do not want to execute the last "print("in tool.py")" of the tool Module , then we can achieve our goal through the following magical judgment statement:

 if __name__ == "__main__":
# code

View all defined names in Module through dir( )

Before understanding what this magical judgment statement actually means, let's first understand what " __name__ " is.

As mentioned above, in a Python program, when the computer executes the "introduced Module" code, two things actually happen:

  1. The computer will create some special variables for this Module (eg: __name__ )
  2. The computer will execute each line of code in the Module

We can see what special variables the computer has set for the Module. We have to add a line of code " print(dir(tool)) " to main.py, so the main.py will look like this:

 # main.py

import tool

print(dir(tool))

tool.func1()
tool.func2()

Then, execute the following command again in Colab to let the computer execute the program main.py:

 !python main.py

We will get the following output:

 in tool.py
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'func1', 'func2']
In func1
In func2

The output of the second line shows all the defined names in the tool Module. Except for "func1" and "func2", which are defined by us, the rest are automatically defined by the computer for us when "import tool" is performed.

Know what the value of __name__ is

The variable "__name__" can be thought of as the name of this Module and this Python file. The values in the __name__ variable can be divided into the following two types:

  • When this Module and this Python file are executed directly, __name__ is set to "__main__"
  • When this Module, this Python file is imported, __name__ is set to "file name"

For example, we add another line of code at the very beginning of tool.py to display the __name__ of tool.py:

 #tool.py

print(f"tool.py __name__: {__name__}")

def func1():
print("In func1")

def func2():
print("In func2")

print("in tool.py")

Next, we go back to the Colab editor and execute the following command to execute main.py:

 !python main.py

will get the following output:

 tool.py __name__: tool
in tool.py
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'func1', 'func2']
In func1
In func2

We can find that when the tool Module is imported, its __name__ will be its file name .

Next, we go back to the Colab editor and execute the following command to execute tool.py:

 !python tool.py

will get the following output:

 tool.py __name__: __main__
in tool.py

We can find that when the tool Module is executed directly, its __name__ will be "__main__" .

By if __name__ == "__main__": avoid part of the code in the Module to be executed when "imported"

I believe you already know what __name__ is and what its value will be. Finally, if we want main.py to import the tool Module, some code in the tool Module should not be executed, we can put these codes under "if __name__ == "__main__"":

 #tool.py

print(f"tool.py __name__: {__name__}")

def func1():
print("In func1")

def func2():
print("In func2")

if __name__ == "__main__":
print("in tool.py")

Execute the following command again in Colab to let the computer execute the main.py program:

 !python main.py

Got the following output:

 tool.py __name__: tool
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'func1', 'func2']
In func1
In func2

yeah! "in tool.py" is gone.

Epilogue

In this article, we introduced what a Module's __name__ is, and the rules for the value stored in __name__. Finally, we also introduce how to avoid part of the code in the Module from being executed when it is "imported" through if __name__ == "__main__".


👣 👣 👣 I like to write articles related to programming and data science. I hope I can explain complex concepts through simple words! If you are also interested, you can visit my other platforms!
👉🏻 DataSci Ocean
👉🏻 YouTube
👉🏻 Instagram
👉🏻 Potato Media

CC BY-NC-ND 2.0

Like my work?
Don't forget to support or like, so I know you are with me..

Loading...

Comment