Dynamically importing Python module Dynamically importing Python module python python

Dynamically importing Python module


It looks like this should do the trick: importing a dynamically generated module

>>> import imp>>> foo = imp.new_module("foo")>>> foo_code = """... class Foo:...     pass... """>>> exec foo_code in foo.__dict__>>> foo.Foo.__module__'foo'>>>

Also, as suggested in the ActiveState article, you might want to add your new module to sys.modules:

>>> import sys>>> sys.modules["foo"] = foo>>> from foo import Foo<class 'Foo' …>>>>


Here's something I bookmarked a while back that covers something similar:

It's a bit beyond what you want, but the basic idea is there.


Python3 version
(attempted to edit other answer but the edit que is full)

import impmy_dynamic_module = imp.new_module("my_dynamic_module")exec("""class Foo:    pass""", my_dynamic_module.__dict__)Foo = my_dynamic_module.Foofoo_object = Foo()# register it on sysimport syssys.modules[my_dynamic_module.__name__] = my_dynamic_module