What Does if __name__ equals “__main__” Do in Python?

What Does if __name__ equals “__main__” Do in Python?


Today, let’s discuss something that’s all over the place in many code bases: what does if __name__ == ‘__main__’ do in Python?

Before executing code, Python interpreter reads source file and define few special variables/global variables.
If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name. Module’s name is available as value to __name__ global variable. A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.


In other Simple words

Every module in Python has a special attribute called __name__. The value of __name__ attribute is set to ‘__main__’ when module run as main program. Otherwise, the value of __name__ is set to contain the name of the module.

Let’s put together this little code example for understanding. Suppose we create two modules, foo and bar with the following code:

# foo.py
import bar
print(“foo.__name__ set to “, __name__)


And the bar module:


# bar.py
print(“bar.__name__ set to “, __name__)


On invoking the bar module from command line, its __name__ attribute will be set to “__main__”:


python bar.py

>>> bar.__name__ set to __main__


However, on invoking the foo module in a similar fashion, the bar’s __name__ attribute will be set equivalent to it’s module name i.e bar:


python foo.py
>>>
bar.__name__ set to bar
foo.__name__ set to __main__


Therefore, we can test whether our module is being run directly or being imported using the following check:


if __name__ == “__main__”:


When a module is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed. To illustrate this, let’s consider the following two modules:


# module person.py
def creds():
name = “Ali”
age = 19
print(“person details {}, {}”.format(name, age))
print(“top-level in person module”)
if __name__ == “__main__”:
print(“person mod is run directly”)
else:
print(“person mod is imported into another module”)


# module utility.py
import person
person.creds()
if __name__ == “__main__”:
print(“utility mod is run directly”)
else:
print(“utility mod is imported into another module”)


On invoking the person module directly, __name__ attribute will be set to __main__, hence we’ll see the following output:


python person.py
>>>
top-level in person module
person mod is run directly


Whereas, when utility.py module is executed directly, __name__ attribute for person module will be set to “person” itself, while __name__ of the utility module will be set to __main__. Therefore, we’ll get the following output


python utility.py
>>>
top-level in person module
person mod is imported into another module
person details Ali, 19
utility mod is run directly


Why it’s designed like this?

We might naturally wonder why it’s designed the way it is. Well, sometimes we want to write a .py file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself.
This behaviour comes in handy for quick developing and testing our code. It also helps in debugging since it allows us to have a script mode where we can run unit tests directly.
Besides this, it’s elegant that running a module in Python directly is just setting up a single variable.


Conclusions:

Every module in Python has a special attribute called __name__. The value of __name__ attribute is set to “__main__” when module is run as main program. Otherwise, the value of __name__ is set to contain the name of the module. We use if __name__ == “__main__” block to prevent (certain) code from being run when the module is imported.


Learn Python programming from scratch through Python programming certification course. This Python Course will help you master important Python programming concepts such as data & file operations in Python, object-oriented concepts in Python & various Python libraries such as Pandas, Numpy, Matplotlib, and so on. This Python certification course is also a gateway towards your Data Science career. The course is curated by industry experts which includes real-time case studies. Enroll & Get Certified now!



Drop us a Query

About the author

Bhaskar

Bhaskar

The author has a keen interest in exploring the latest technologies such as AI, ML, Data Science, Cyber Security, Guidewire, Anaplan, Java, Python, Web Designing tools, Web Development Technologies, Mobile Apps, and whatnot. He bags over a decade of experience in writing technical content.

Corporate
whatsapp arrow
Loading...
// load third party scripts onload