Search code examples
pythonimportmoduleexeceval

Python import via exec does not work, while hardcoded import works


Inside a function, I have to import a variable (dict) from a module dynamically:

exec("from ctrl_%s import default_settings" % get_version_id(iid))

which doesnt work. When referencing this variable later, it says: UnboundLocalError: local variable 'default_settings' referenced before assignment

The variable is in the global scope of the module to import.

But:

This all works, if I hardcode this statement without exec(). The string is correctly formed, I can print it out.

Someone knows what to do?


Solution

  • I highly would discourage to use exec in the first place, it often does not do what you want especially if some special syntax is involved like here.

    But fortunately there are some tricks:

    e.g. you can import the module and use the dict or getattr:

    import math 
    
    getattr(math,"sin")                                                                                                                  
    
    math.__dict__['sin']
    
    

    Edit just checked my answer and I saw you wanted to import a module ... But there is also a trick for this:

    https://docs.python.org/3/library/functions.html#__import__

    Look also at this question for some examples: How to import a module given its name as string?