How are main .py files processed by the python interpreter?

I recently tried to dig deeper into the python core. I am currently exploring the pythons module system and storing "global", "local" and "non-local" variables. More specifically, my question is, how does the interpreter handle the file that is being run? Is it treated as a native module in modules (or something similar)?

+3


source to share


2 answers


The top level script is considered a module, but with a few differences.

  • Instead of a name being a script name minus an extension .py

    , its name __main__

    .
  • The top level script is not seen in the cache .pyc

    , compiled or cached there.

Also, it's basically the same: the interpreter compiles your script as a module, builds from it types.ModuleType

, stores it in sys.modules['__main__']

, etc.

Also see runpy

which explains how python spam.py

and python-m spam

. (As of, I think 3.4, runpy.run_path

should do the same as using a script, not just something very similar.) And note that the docs link to the source , so if you need to find any specifics of internals, You can.




The first difference is why you see this idiom often:

if __name__ == '__main__':
    import sys
    main(sys.argv) # or test() or similar

      

This allows the same file to be used spam.py

as a module (in which case it __name__

will be spam

) or as a script (in which case it __name__

will be __main__

), with code you only want to use in the case of a script.




If you're wondering if the interactive interpreter's standard input is treated the same as a script, there are a lot more differences. Most importantly, each statement is compiled and run as a c statement exec

, not the entire script / module that is compiled and run as a module.

+3


source


Yes , which is essentially happening. This is a module __main__

. You can see this by doing something like the following:

x = 3
import __main__
print(__main__.x)

      



Either run as a script file or on an interpreter, this will print:

3

      

0


source







All Articles