开发者

Importing everything ( * ) dynamically from a module

开发者 https://www.devze.com 2023-01-24 08:09 出处:网络
I have a Python module that I want to dynamically import given only a string of the module name. Normally I use importlib or __import__ and this works quite well given that I know which objects I want

I have a Python module that I want to dynamically import given only a string of the module name. Normally I use importlib or __import__ and this works quite well given that I know which objects I want to import from the module, but is there a way to do开发者_Go百科 the equivalent of import * dynamically. Or is there a better approach?

I know in general its bad practice to use import * but the modules I'm trying to import are automatically generated on the fly and I have no way of knowing the exact module which contains the class I'm addressing.

Thanks.


Use update for dicts:

globals().update(importlib.import_module('some.package').__dict__)

Note, that using a_module.__dict__ is not the same as from a_module import *, because all names are "imported", not only those from __all__ or not starting with _.


I came up with some ugly hacky code, it works in python 2.6. I'm not sure if this is the smartest thing to do though, perhaps some other people here have some insight:

test = __import__('os',globals(),locals())
for k in dir(test):
    globals()[k] = test.__dict__[k]

You probably want to put a check here to make sure you aren't overwriting anything in the global namespace. You could probably avoid the globals part and just look through each dynamically imported module for your class of interest. This would probably be much better than polluting the global namespace with everything you are importing.

For example, say your class is named Request from urllib2

test = __import__('urllib2',globals(),locals())
cls = None
if 'Request' in dir(test):
    cls = test.__dict__['Request']
    # you found the class now you can use it!
    cls('http://test.com')


The following is highly sinful and will condemn you to purgatory or worse

# module_a.py
myvar = "hello"

# module_b.py
import inspect
def dyn_import_all(modpath):
    """Incredibly hackish way to load into caller's global namespace"""
    exec('from ' + modpath + ' import *', inspect.stack()[1][0].f_globals)

# module_c.py
from module_b import dyn_import_all
def print_from(modpath):
    dyn_import_all(modpath)
    print(myvar)

Demo:

>>> import module_c
>>> module_c.print_from("module_a")
hello
0

精彩评论

暂无评论...
验证码 换一张
取 消