pythonpython-importbrownie

How do I dynamically import a module similar to the "import X from Y" syntax in Python?


I'm trying to achieve:

from X import Y

where Y is a string name of a module that is only known during runtime.

I've tried using

module = importlib.import_module(Y, X)

But that doesn't work. I also don't know the path of the module as it only exists during runtime within the module Brownie and is deleted afterward.

Would very much appreciate help.


Solution

  • You almost got it, except that the second argument to import_module is the package name, not the attribute you want. When you want a attribute from a module, you must run the code for the entire module first, since python has no way to predict which lines will have side effects ahead of time.

    So first you import the module:

    X = importlib.import_module('X')
    

    Then you need to get the attribute from the module:

    Y = getattr(module, 'Y')
    

    Of course you probably don't want to create the temprorary variable X, so you can do

    Y = getattr(importlib.import_module('X'), 'Y')