__name__ in Python


I guess, quite often, you see the usage of __name__ in Python. Yes, it is a keyword (attribute) associate to a module. It can be used to tell if the module is being run as stand-alone by the user.

#!/usr/bin/env python

if __name__ == "__main__":
    print "standalone"
else:
    print "imported", __name__

Save this as test.py and press F5 in the IDLE, you will have the “standalone” printed.

In the IDLE, type in import test, you will have “imported test” printed.

[Every Python module has it's __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.]

Experiments directly under the Python shell are shown below.

>>> __name__
"__main__"
>>> test.__name__
"test"
>>> 

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
195 words
Last Post: Bogo Sort Algorithm
Next Post: Codeforces: A. Soft Drinking

The Permanent URL is: __name__ in Python

Leave a Reply