top of page
Writer's pictureThe Tech Platform

What is "__Name__" in Python?

Updated: Jun 16, 2022



"__name__" is a built-in variable in python that stores the name of the current module/script being executed. If the current module is executing then the __name__ variable is assigned the value __main__ otherwise it simply contains the name of the module or script.


Python "__name__" is a special variable in which the name of the current python script/module being executed is stored. It is not available in Python 2.x version and was introduced in Python 3.0 version.


In python, the "__name__" variable is assigned value __main__ for the current python script or module, when it is being executed.


Define the Function

def something():
    print('Value of __name__:', __name__)
    
something()

Why to Choose?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.


How to Use "__Name__ == __Main__"?

To specify some code in any python script which should be executed only when that script is executed directly, we can use the if statement with the condition __name__ == __main__


For example,

# importing test.py
import test  

if __name__ == __main__:     
    test.something()

Here __main__ is just a string that is used to check if the current module/script is running on its own or not. In the __name__ variable, the double underscores on both sides of name is for indicating the python interpreter to recognize it as a special/reserved keyword.


Advantages:

  1. Every Python module has its __name__ defined and if this is ‘__main__’, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.

  2. If you import this script as a module in another script, the __name__ is set to the name of the script/module.

  3. Python files can act as either reusable modules or as standalone programs.

  4. if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.


The Tech Platform

Recent Posts

See All

Comments


bottom of page