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 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.
The following is highly sinful and will condemn you to purgatory or worse
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:
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
Use
update
for dicts:Note, that using
a_module.__dict__
is not the same asfrom a_module import *
, because all names are "imported", not only those from__all__
or not starting with_
.