DEV Community

Cover image for What really is "__name__" (A Special variable) in Python🤔?
Felix DUSENGIMANA
Felix DUSENGIMANA

Posted on

What really is "__name__" (A Special variable) in Python🤔?

Are you a Pythonista? if so, let's clearly dive into what "_name_" and "_main_" really is and how it works.

Let's say you've this code in file1:

# File1.py 

print ("File1 __name__ = %s" %__name__) 

if __name__ == "__main__": 
    print ("File1 is being run directly")
else: 
    print ("File1 is being imported")
Enter fullscreen mode Exit fullscreen mode

And of course this one in file2:

# File2.py

import file1

print("File2 __name__ = %s" % __name__)

if __name__ == "__main__":
    print("File2 is being run directly")
else:
    print("File2 is being imported")
Enter fullscreen mode Exit fullscreen mode

if you run file one the output will be:

File1 __name__ = __main__
File1 is being run directly
Enter fullscreen mode Exit fullscreen mode

And if you run file2 output will be:

File1 __name__ = file1
File1 is being imported
File2 __name__ = __main__
File2 is being run directly
Enter fullscreen mode Exit fullscreen mode

If you've seen the output carefully, the *_name_ * is a built-in variable which evaluates to the name of the current module.

You may ask why it sometimes returns _main_🤔?,

If the current script is being run on its own, the _name_ variable returns *main * and if the script is imported the _name_ will returns module name.

REMARK: _name_ is always a string datatype.

Let's consider example above if you run file 2, the _name_ variable in file1 will be file1 because that's the name of module we are importing, and _name_ in file2 will be __main__ as it's the module we're running.

You can use the _name_ variable a get name of a class you've imported. example

from player import Player

print(Player.__name__) 
# OUTPUT: Player
Enter fullscreen mode Exit fullscreen mode

To summarize all we said above, 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.

Thanks to this special variable, you can decide whether you want to run the script. Or that you want to import the functions defined in the script.

Top comments (0)