An introduction to the __name__ variable
You probably seen the
__name__ variable if you’ve gone through some python
open source code. For instance below:
Whenever the python interpreter reads a source file, it does two things:
- sets a few special/global variables like
- executes all of the code found in the file.
Why is the __name__ variable used?
__name__ is a special python variable. It gets it’s value depending on how
we execute the containing module.
Sometimes you write a module with functions that might be useful in other module as well. In python, you can import that module into another module.
Thanks to this special variable, you can decide whether you want to run the the whole module. Or you want to import the functions defined in the module.
To grasp the context more vividly let see some use case examples.
Let’s assume that we have module which has a simple function called
get the maximum integer in a given array:
if we run this module we get the below result:
$ python module_one.py Hello Module 1 max int: 9
So now assume that we need this
get_max() function from other module that we
If we now run the
module_two.py we get the output:
$ python module_two.py Hello Module 1 max int: 9 Hello Module 2 max int: 17
According to our program, the output should be “17” because the
get_max() function is called. But the whole module is imported.
To overcome this we use
if __name__ == “__main__”. The extra line of codes
written after function
module_one.py is kept inside of it so it
won’t be executed while the function is imported in
Now update our
module_one.py like below:
Now run the
$ python module_two.py Hello Module 2 max int: 17
You see that after using
if __name__ == “__main__” the unreletad codes will
not be used by
After all that we understand that what does
if __name__ == “__main__” do in
python; it prevents certain code to run if any other file import it.