exec and globals and locals ...

Peter Otten __peter__ at web.de
Thu Sep 19 02:47:43 EDT 2019


Eko palypse wrote:

> exec('import test01', globals())
> print('f3 out', x)
> 
> # result exception, expected but because f1 didn't throw an exception
> # I'm confused. module test01 has only this two lines
> x += 1
> print('f3 in:', x)

The lines above run in the test01's global namespace, not in the global 
namespace of the importing module.

> exec('import test01', globals())

Think of import as a function like

exec("test01 = load_module('test01')", globals())

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.





More information about the Python-list mailing list