How to correctly understand if __name__ == '__main__' in python?

In Python, we often write (Note: the content is excerpted from youzhouliu, thank him here)

[python]  view plain copy  
  1. if __name__ == '__main__'   
Such a piece of code, how to understand this code?

The function of this code is understood as follows:

A python file can be used in two ways:

The first function is to execute it directly as a script.

The second function is to import into other python scripts and be called (module reuse) for execution.

The role of if __name__ == '__main__': is to control the process of executing code in these two cases. The code under if __name__ == '__main__': will only be executed in the first case (that is, the file is directly executed as a script) is executed, but imports into other scripts will not be executed.


How it works

Each python module (python file) contains the built-in variable __name__, which is equal to the filename (including the suffix .py) when the run module is executed. If imported into other modules, __name__ is equal to the module name (without the suffix .py). And "__main__" is equal to the name of the current execution file (including the suffix .py). So when the module is executed directly, the result of __name__ == '__main__' is true; and when the module is imported into other modules, the result of __name__ == '__main__' is false, that is, the corresponding method is not called.


In short: __name__ is the current module name, and the module name is __main__ when the module is run directly. When the module is run directly, the code will be run, when the module is imported, the code will not be run.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645268&siteId=291194637