exec and globals and locals ...
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,
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__)
>>> sys.modules["module"] = module
>>> import module
The importlib probably has an official way, but I've yet to wrap my head
around that part of Python.