Andrew Bezzub
Andrew Bezzub

Reputation: 16032

Dynamically load all names from module in Python

How do I do from some.module import * where name of the module is defined in a string variable?

Upvotes: 2

Views: 346

Answers (2)

Phillip
Phillip

Reputation: 13668

This code imports all symbols from os:

import importlib
# Load the module as `module'
module = importlib.import_module("os")
# Now extract the attributes into the locals() namespace, as `from .. 
# import *' would do
if hasattr(module, "__all__"):
    # A module can define __all__ to explicitly define which names
    # are imported by the `.. import *' statement
    attrs = { key: getattr(module, key) for key in module.__all__ }
else:
    # Otherwise, the statement imports all names that do not start with
    # an underscore
    attrs = { key: value for key, value in module.__dict__.items() if
              key[0] != "_" }
# Copy the attibutes into the locals() namespace
locals().update(attrs)

See e.g. this question for more information on the logic behind the from ... import * operation.

Now while this works, you should not use this code. It is already considered bad practice to import all symbols from a named module, but it certainly is even worse to do this with a user-given name. Search for PHP's register_globals if you need a hint for what could go wrong.

Upvotes: 2

planet260
planet260

Reputation: 1454

In Python the built-in import function accomplishes the same goal as using the import statement, but it's an actual function, and it takes a string as an argument.

sys = __import__('sys')

The variable sys is now the sys module, just as if you had said import sys.

Reference

Upvotes: 0

Related Questions