osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

exec and globals and locals ...


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.