David Cramer
David Cramer

Reputation: 1998

How to import * with __import__

What's the best approach to execute the following using __import__ so that I may dynamically specify the module?

from module import *

Upvotes: 17

Views: 4829

Answers (3)

David Cramer
David Cramer

Reputation: 1998

The only way I found:

module = __import__(module, globals(), locals(), ['*'])
for k in dir(module):
    locals()[k] = getattr(module, k)

Upvotes: 17

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

__import__() never adds anything to the local scope. You will have to go through the returned module, accessing its attributes as desired.

Upvotes: 5

Michael Mrozek
Michael Mrozek

Reputation: 175365

It's the same as a normal from-import call, you just pass it a list containing '*' for the fromlist:

moduleName = "foo"
__import__(moduleName, globals(), locals(), ['*'])

Upvotes: 5

Related Questions