2
/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?

14
  • 2
    Is there a reason you want to use exec() for this? Aug 2, 2018 at 16:17
  • 1
    drawing_class = getattr(__import__(module_name), chart_type) means you don't need any exec() usage or other eval equivalents. Aug 2, 2018 at 16:18
  • 1
    I'm not sure why upgrading means you need to use exec. __import__ and getattr still work in Python 3. Aug 2, 2018 at 16:57
  • 1
    @CharlesDuffy I guess he is dynamically importing class which is why he may require exec, I am also stuck in the same issue Aug 21, 2018 at 11:08
  • 2
    ...so, I do need to revise my prior comment to suggest 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. Aug 21, 2018 at 12:30

1 Answer 1

1

Consider the following configuration, importing code from the standard library:

module_name = 'logging.config'
chart_type = 'dictConfig'

This works properly when invoking:

import importlib
drawing_class = getattr(importlib.import_module(module_name), chart_type)

...thus avoiding any need for exec at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.