import module from string variable

前端 未结 5 1684
离开以前
离开以前 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:38

    Apart from using the importlib one can also use exec method to import a module from a string variable.

    Here I am showing an example of importing the combinations method from itertools package using the exec method:

    MODULES = [
        ['itertools','combinations'],
    ]
    
    for ITEM in MODULES:
        import_str = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:]))
        exec(import_str)
    
    ar = list(combinations([1, 2, 3, 4], 2))
    for elements in ar:
        print(elements)
    

    Output:

    (1, 2)
    (1, 3)
    (1, 4)
    (2, 3)
    (2, 4)
    (3, 4)
    

提交回复
热议问题