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)
    exec import_str
except ImportError:
    print 'import failed:', import_str
    from pprint import pprint
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