python - exec a global variable from an extern module -
i have extern module want set "exec" expressions global (because need pass strings variables names)
so, have function like
def fct_in_extern_module(): exec 'a = 42' in globals() return none
and in main script have
import extern_module extern_module.fct_in_extern_module()
thus, why have
nameerror: name 'a' not defined
while if (in main script)
def fct_in_main(): exec 'b = 42' in globals() fct_in_main() >>> b 42
any idea how can affect set string 'a' variable name in extern module ?
thanks !
globals()
means "the globals dict of this module". thus, way have chosen code extern_module.py
not affect globals dict of other module.
one way fix: define as:
def fct_in_extern_module(where): exec 'a = 42' in
and call as:
extern_module.fct_in_extern_module(globals())
of course, usual, exec
not best way solve problem. better:
def fct_in_extern_module(where): where['a'] = 42
faster , cleaner.
Comments
Post a Comment