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.

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:
    from pprint import pprint
    pprint(locals())
Did this help you? Please let me know with a comment. Thank you
Posted .

2 comments (RSS)

  1. anonymous

    That's a nice post.

  2. anonymous

    This looks way too easy compared to all the other solutions I've found so far ... :O

Leave a comment