How to Lazy-Load a Python Module Import with Example
To dynamically load or lazy-load a python module, do the following:
import_str = 'from pprint import pprint'
exec(import_str)
A more complete example with error catching.
import pprint
module_name = 'bar'
definition = 'my_method'
import_str = 'from foo.{0} import {1}'.format(module_name, definition)
try:
exec(import_str)
except ImportError:
print('import failed:', import_str)
else:
pprint.pprint(locals())
2 comments
That's a nice post.
This looks way too easy compared to all the other solutions I've found so far ... :O
Leave a Reply