Python __name__ global variable (newbie question)

What are the following names when python shell is first run? They are not like functions from __builtins__:

>>> dir(__name__)

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', 
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
 '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 
'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace',
 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']
+3
source share
2 answers

__name__is a string and those string methods. This is the name of the module or '__main__'at the top level. Therefore, this idiom appears often:

if __name__ == '__main__':
    # this file was called directly, not imported
    main()
+8
source

dir(__name__)shows attributes __name__, and since it __name__is a string, it shows class attributes str. Most of the attributes listed are methods. You can get additional information using help():

>>> help(str.index)
Help on method_descriptor:

index(...)
    S.index(sub [,start [,end]]) -> int

    Like S.find() but raise ValueError when the substring is not found.
+5
source

All Articles