exec and globals and locals ...

Eko palypse ekopalypse at gmail.com
Thu Sep 19 07:05:02 EDT 2019


Am Donnerstag, 19. September 2019 12:56:59 UTC+2 schrieb Peter Otten:
> Eko palypse wrote:
> 
> >> Then it should be clear that the name 'test01' is put into globals(), if
> >> load_module() doesn't throw an exception. No sharing or nesting of
> >> namespaces takes place.
> > 
> > Thank you too for your answer. Ok, that means that in every case when exec
> > imports something it has its own global namespace, right?
> > Is there a way to manipulate this namespace before any code from that
> > module gets executed?
> 
> Create a module object, preload its namespace, then exec the module's code, 
> like:
> 
> $ python3
> Python 3.4.3 (default, Nov 12 2018, 22:25:49) 
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import sys, types
> >>> module = types.ModuleType("module")
> >>> module.x = 42
> >>> exec("print(x)\ndef f(): return x * x", module.__dict__)
> 42
> >>> sys.modules["module"] = module
> >>> import module
> >>> module.f()
> 1764
> 
> The importlib probably has an official way, but I've yet to wrap my head 
> around that part of Python.

Thank you, I'm currently investigating importlib and read that __builtins__
might be another alternative.
My ultimate goal would be to have objects available without the need to import them, regardless whether used in a script directly or used in an imported module.

Eren



More information about the Python-list mailing list