9

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.

4 Answers 4

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 I'm using builtins rather than globals() so that I can use this code from another module.
9
__import__("foo", fromlist=["bar"])

for more information help(__import__)

1 Comment

Thanks. Is there a way to emulate "from foo import *"?
1

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

1 Comment

Thanks. Is there a way to emulate "from foo import *"?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.