Hello,
On Tue, 1 Dec 2020 10:59:04 -0500
Ricky Teachey
Hi Paul it's an interesting proposal. I have a couple clarifying questions about it.
On Tue, Dec 1, 2020 at 10:32 AM Paul Sokolovsky
wrote: Effectively, with the current Python execution model, all code is executed at "import-time". This proposal seeks to introduce well-defined distinction between import-time vs run-time. For this, it introduces the `__main__()` function, localted in the `__main__` module of the application (from which application execution starts). All top-level code in the `__main__` module is executed to completion, including code in recursively imported modules. This completes the "import-time" phase of the application. After that, the `__main__()` function is executed, which begins the "run-time' phase.
Two questions about this.
1. What about single module packages? If there is no __main__ module, how does the interpreter find my __main__() function?
The application main module loading happens as usual (whether it's file.py or -m module switch is used). It's just normally, after main module top-level code finishes execution, the interpreter exits (because the application exited). In strict mode instead, interpreter looks up __main__() function in this main module, and executes it.
2. In order to maintain the distinction between "import time" and "run time", will it be illegal to explicitly run __main__() in the __main__ module at import time? If not, would __main__() still be run (a *second time*) at run time....?
Even the "TL;DR" version gives the idiom to make an application (its main module) be compatible with both standard and strict mode. And full version gives the details of why it is so. That's pretty much the simple(st) method, why do you ask for something else?
``` __
# import time section
def __main__(): # run time print("foo")
__main__() ```
Is the output:
foo foo
Yes, if run in the strict mode, the __main__() will be executed twice.
...or it is just:
foo
...?
## Discussion and implications
The baseline implications should be fairly obvious from the text above:
``` def fun(): pass
# This (defining the function of the same name) will lead to warning # at import-time. def fun(): pass
import mod
# This (assigning to a var in another module) is possible # both at import-time and run-time. mod.var = 1
# This will lead to warning at import-time and RuntimeError at runtime. mod.func = lambda *a, **kw: print("Stabbed out!") ```
In the above code snippet, are you assuming that mod.func already exists, and the last line in the module is redefining the existing mod.func, and this is what causes the runtime error?
Yes, that's it.
--- Ricky.
-- Best regards, Paul mailto:pmiscml@gmail.com