Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are basic .py files treated by the python interpreter?

Tags:

python

Recently I have been trying to dig deeper into the core of python. Currently I am look into pythons module system and how "global", "local", and "nonlocal" variables are stored. More specifically, my question is how does the interpreter treat the file being run? Is it treated as its own module in the modules (or something similar)?

like image 915
Ian Leaman Avatar asked Mar 15 '26 13:03

Ian Leaman


1 Answers

The top-level script is treated as a module, but with a few differences.

  • Instead of its name being the script name minus a .py extension, its name is __main__.
  • The top-level script does not get looked up in the .pyc cache, nor compiled and cached there.

Other than that, it's mostly the same: the interpreter compiles your script as a module, builds a types.ModuleType out of it, stores it in sys.modules['__main__'], etc.

Also look at runpy, which explains how both python spam.py and python-m spam work. (As of, I think, 3.4, runpy.run_path should do exactly the same thing as running a script, not just something very similar.) And notice that the docs link to the source, so if you need to look up any specifics of the internals, you can.


The first difference is why you often see this idiom:

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

That allows the same file spam.py to be used as a module (in which case its __name__ will be spam) or as a script (in which case its __name__ will be __main__), with code that you only want to be run in the script case.


If you're curious whether standard input to the interactive interpreter is treated the same way as a script, there are a lot more differences there. Most importantly, each statement is compiled and run as a statement with exec, rather than the whole script/module being compiled and run as a module.

like image 103
abarnert Avatar answered Mar 18 '26 03:03

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!