import module from string variable

前端 未结 5 1676
离开以前
离开以前 2020-11-22 07:17

I\'m working on a documentation (personal) for nested matplotlib (MPL) library, which differs from MPL own provided, by interested submodule packages. I\'m writing Python sc

5条回答
  •  感情败类
    2020-11-22 07:41

    The __import__ function can be a bit hard to understand.

    If you change

    i = __import__('matplotlib.text')
    

    to

    i = __import__('matplotlib.text', fromlist=[''])
    

    then i will refer to matplotlib.text.

    In Python 2.7 and Python 3.1 or later, you can use importlib:

    import importlib
    
    i = importlib.import_module("matplotlib.text")
    

    Some notes

    • If you're trying to import something from a sub-folder e.g. ./feature/email.py, the code will look like importlib.import_module("feature.email")

    • You can't import anything if there is no __init__.py in the folder with file you are trying to import

提交回复
热议问题