Search code examples
pythonpython-3.xpython-module

When we open an interactive python3 interpreter and run some commands, do we run the commands in some module?


When we open an interactive python3 interpreter and run some commands, do we run the commands in some module? What is that module?

I ask this because __name__ is __main__ in such cases, and I think __name__ is an attribute of some module which I don't know and am asking for. But __dict__ and __file__ as attributes of a module don't exist. The attributes which exist are:

>>> globals()
{'__package__': None, '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__',   '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}

Solution

  • Yes, the interpreter session is the __main__ module:

    $ python3.6
    Python 3.6.1 (default, Apr  5 2017, 20:56:42)
    [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.modules['__main__']
    <module '__main__' (built-in)>
    >>> sys.modules['__main__'].__dict__ is globals()
    True
    

    The globals() object is the module __dict__ namespace. Don't confuse the contents of the namespace with the namespace itself (when you ask for the attributes of an instance, __dict__ is not inside the instance __dict__ attribute either).

    The __file__ attribute is optional; since you are not running from a file here, the attribute is not set:

    >>> sys.modules['__main__'].__file__
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: module '__main__' has no attribute '__file__'