/my/charts/
|- module/
|-abc.py
|- runtest.py
|- main.py
|- sample.py
I am trying to call main.py from runtest.py. in that, I want to import abc.py using exec:-
module_name = 'module.abc'
chart_type = 'abc'
exec('from {} import {} as drawing_class'.format(module_name,chart_type))
When I run the code it is not giving any error but when I print dir(drawing_class) or drawing_class at next line of exec then it gives an error. like NameError: name 'drawing_class' is not defined
But when I wrote the same exec code in sample.py then it is working as per expected.
Why is this exec not working in main.py?
exec()
for this?drawing_class = getattr(__import__(module_name), chart_type)
means you don't need anyexec()
usage or othereval
equivalents.exec
.__import__
andgetattr
still work in Python 3.importlib.import_module
rather than__import__
, but with that done,module_name = 'logging.config'; chart_type = 'dictConfig'; import importlib; drawing_class = getattr(importlib.import_module(module_name), chart_type)
works perfectly. I've yet to see a minimal reproducible example here -- code someone other than the OP can copy-and-paste (without doing a bunch of work like setting up a module structure that reproduces theirs) to see their problem.