If __name__ == '__main__':

Hello everyone,

i saw often in some tutorials the code in title.
What is the main purpose of the following code:

if name == ‘main’:

and when I sould it using ?

Thanks so lot.

Best Regards

Hi Tugrul,

Every module in Python has a __name__ attribute. When you run your program from the current file you are in, this attribute will be set to ‘main’. However, when you import a module, this attribute will be set to the name of that module (e.g., ‘ecommerce.shopping.sales’).

The main purpose of using the construct if __name__ == '__main__': is to separate the code that should be executed when the script is run directly, from the code that is meant to be imported. When you import another module, the code in that module will be executed when you execute your root script that did the importing. ie: if you have print() functions in the imported module, those print functions will be run when you execute this root script. This might not always be desired, sometimes, we only want to reference variables and functions declared in the imported module not call the functions there.

I recommend watching Mosh’s lecture on ‘executing modules as scripts’ in the modules section of the complete Python mastery course for a more detailed explanation and practical examples. Experimenting with both if __name__ == '__main__': and if __name__ != '__main__': will help you understand how your program behaves differently in these scenarios.

Well, if_ name == main _ is a common construct in python script and main purpose of this construct is to control the execution of code within a python file.
For example:

# This code will only run if this script is executed directly.
if __name__ == "__main__":
    # This code block contains the script's entry point.
    # You can put function calls and other script-specific logic here.
    print("This script is being run directly.")