David542
David542

Reputation: 110163

Python3 global dir

When entering in the python3.6 shell dir produces the following:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

__builtins__ produces all the built-in python methods, for example those described here, and __name__ will (always?) be __main__. What about the others: are those ever populated when either (1) in the python interpreter; or (2) running a script: and if so, when?

Here's an example from running a python script called temp.py:

if __name__ == '__main__':
    print (dir())
    print ("__annotations__: %s" % __annotations__)
    print ("__builtins__: %s" % __builtins__)
    print ("__cached__: %s" % __cached__)
    print ("__doc__: %s" % __doc__)
    print ("__file__: %s" % __file__)
    print ("__name__: %s" % __name__)
    print ("__package__: %s" % __package__)
    print ("__spec__: %s" % __spec__)

Running it:

$ python temp.py
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
 __annotations__: {}
__builtins__: <module 'builtins' (built-in)> # <== always populated
__cached__: None
__doc__: None
__file__: temp.py # <== populated if running from a file/script
__name__: __main__ # <== populated (always with main?)
__package__: None

How/when are __annotation__, __cached__, __doc__, __package__ populated? And is __name__ ever not __main__ ?

Upvotes: 1

Views: 153

Answers (1)

Aaron A
Aaron A

Reputation: 495

__name__ is only __main__ in the script that is being run. It holds the fully-qualified name of the module where it is accessed:

>>> __name__
'__main__'
>>> from logging import config
>>> config.__name__
'logging.config'

__cached__ and __package__ are Import-related module attributes.

__doc__ holds the docstring of the current module or function.

__annotations__ holds annotations of globals.

Upvotes: 1

Related Questions