exec and globals and locals ...

Peter Otten __peter__ at web.de
Thu Sep 19 06:56:36 EDT 2019


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.




More information about the Python-list mailing list