Dynamically importing Python modules

2020-02-13 18:07发布

问题:

I am trying to import the members of a module whose name is not known. Instead of

import foo

I am using:

__import__("foo")

How can I achieve a similar thing for the from foo import bar case instead of resorting to an "eval"?

Update: It seems fromlist did the trick. Is there a way to emulate from foo import *? fromlist=['*'] didn't do the trick.

回答1:

To emulate from foo import * you could use dir to get the attributes of the imported module:

foo = __import__('foo')
for attr in dir(foo):
    if not attr.startswith('_'):
        globals()[attr] = getattr(foo, attr)

Using from foo import * is generally frowned upon, and emulating it even more so, I'd imagine.



回答2:

__import__("foo", fromlist=["bar"])

for more information help(__import__)



回答3:

You can dynamically import with the help of __import__. There are fromlist key argument in __import__ to call from foo import bar.



回答4:

Sometimes you want to import one of many configuration files, each of which had different values for the same named variables, dicts, etc.

You can't just do this:

def mother_function(module, *args, **kwargs):
    from module import variable
    return variable

def call_home_to_mamma():
    import module_42
    return mother_function(module_42)

The explanation as to why this doesn't work is above my pay grade, and involves closures and namespaces. What I found worked was to call the mother function with 'module_name' as a string argument, then dyamically import the particular variable when I really needed it:

def mother_function(module_name, *args, **kwargs):
    exec('from %s import %s' % (module_name, variable))
    variable = eval(variable)
    return variable

def call_home_to_mamma():
    import module_42
    return mother_function(module_42.__name__)

Bingo.... you have dyamic import of any variable you want, from an imported module as determined at runtime.



标签: python import