[Python] if name == 'main' detailed explanation


Article Directory


insert image description here


if name == 'main': Used in Python to determine whether the module is run directly.

In Python, a module (.py file) can either be imported and used as a module, or run directly as a standalone program. When a module is imported, the Python interpreter executes the entire module's code, including the code in the if name == 'main': block. This will cause some unnecessary code to be executed.

The code inside the if name == 'main': block will only be executed when the module is run directly, not when it is imported. Therefore, we can place code in the if name == 'main': block that we want to be executed when the module is run directly, including test code, etc.

For example, assuming we have a module called my_module, we can test it in an if name == 'main': block:

# my_module.py
def my_function():
    print('hello from my_function')

if __name__ == '__main__':
    print('hello from my_module')
    my_function()

When we run the my_module.py file directly, the code in the if name == 'main': block will be executed. But if we import the my_module module in another file, the code inside the if name == 'main': block will not be executed.

Guess you like

Origin blog.csdn.net/guanguan12319/article/details/130000209