[Python-ideas] proposal: "python -m foo" should bind sys.modules['foo']

Cameron Simpson cs at zip.com.au
Wed Jan 18 00:21:04 EST 2017


Trying to get back to speed with PEP-499...

On 06Aug2015 13:26, Nick Coghlan <ncoghlan at gmail.com> wrote:
>On 6 August 2015 at 10:07, Cameron Simpson <cs at zip.com.au> wrote:
>> I suspect "How Reloading Will Work" would need to track both module.__name__
>> and module.__spec__.name to reattach the module to both entires in
>> sys.modules.
>
>Conveniently, the fact that reloading rewrites the global namespace of
>the existing module, rather than creating the new module, means that
>the dual references won't create any new problems relating to multiple
>references - we already hit those issues due to the fact that modules
>refer directly to each from their module namespaces.
[...]
>> Also, where do I find to source for runpy to preruse?
>
>It's a standard library module:
>https://hg.python.org/cpython/file/default/Lib/runpy.py
>
>"_run_module_as_main" is the module level function that powers the "-m" switch.
>
>Actually *implementing* this change should be as simple as changing the line:
>
>    main_globals = sys.modules["__main__"].__dict__
>
>to instead be:
>
>    main_module = sys.modules["__main__"]
>    sys.modules[mod_spec.name] = main_module
>    main_globals = main_module.__dict__

I'd just like to check that my thinking is correct here. The above looks very 
easy, but Joseph Jevnik pointed out that packages already do this correctly 
(and slightly differently, as __main__ is the main module and __init__ is what 
is in sys.modules):

  https://bitbucket.org/cameron_simpson/pep-0499/commits/3efcd9b54e238a1ff7f5c5df805df13

I'm about to try this:

[~/s/cpython-pep499(hg)]fleet*> hg diff
diff --git a/Lib/runpy.py b/Lib/runpy.py
--- a/Lib/runpy.py
+++ b/Lib/runpy.py
@@ -186,7 +186,10 @@ def _run_module_as_main(mod_name, alter_
     except _Error as exc:
         msg = "%s: %s" % (sys.executable, exc)
         sys.exit(msg)
-    main_globals = sys.modules["__main__"].__dict__
+    main_module = sys.modules["__main__"]
+    if not main_module.is_package(mod_spec.name):
+        sys.modules[mod_spec.name] = main_module
+    main_globals = main_module.__dict__
     if alter_argv:
         sys.argv[0] = mod_spec.origin
     return _run_code(code, main_globals, None,

locally. Does this seem sound?

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Python-ideas mailing list