What is “__name__” and “__main__” in Python?

A guide to unravel the mystery behind the Python code of __name__ and __main__

Jayashree domala
Level Up Coding

--

What does this line of code mean?

if __name__ == “__main__”:

The whole idea behind this line of code is that when you are importing from a module, you would like to know whether a module’s function is being used as an import or if you are using the original “.py” file of that module. In such cases, we use the above line.

When your script is run by passing it as a command to the Python interpreter:

python myscript.py

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are defined but none of their code gets ran. Unlike other languages, there’s no main() function that gets run automatically- the main() function is implicitly all the code at the top level.

__name__ is a built-in variable which evaluates to the name of the current module. This variable gets assigned a string depending on how we are running the actual script.

If a module is being run directly (as in myscript.py above), then __name__ instead is set to the string “__main__”. Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == “__main__”:

If that code is being imported into another module, the various function and class definitions will be imported, but the main() code won’t get run.

To understand it better create two python files “test1.py” and “test2.py”. In test1 we define a function and in test2 we import the tes1 script.

test1.py (Source: Author)
test2.py (Source: Author)

Now when we run test1 script directly from the command line we get the below output from which we can make out that when we run scripts directly __name__ is assigned string __main__.

test1.py output(Source: Author)

Now when we run test2 script, the test1 script is called indirectly by importing it and therefore the ‘else’ statement runs and print that it is being imported into another module. Whereas, test2 script is being run directly so it prints that is run directly.

test2.py output (Source: Author)

Beginner-level books to refer to learn Python:

Advance-level books to refer to learn Python:

Reach out to me: LinkedIn

Check out my other work: GitHub

--

--

Self-driven woman who wishes to deliver creative and engaging ideas and solutions in the field of technology.