Python, import string of Python code as module

Unfortunately, the imp module was recently deprecated (I have NO idea why).

Instead, you should do this:

from types import ModuleType
import sys

mod = ModuleType('my_module', 'doc string here')
exec('a = 1', mod.__dict__)
print(mod.a) # prints 1
# add to sys.modules
sys.modules['my_module'] = mod

Or you can use PyExt's RuntimeModule.from_string:

from pyext import RuntimeModule

mod = RuntimeModule.from_string('a = 1')
print(mod.a) # 1

Here's an example of dynamically creating module objects using the imp module