import from a string

Matt McCredie mccredie at
Tue Nov 3 18:49:43 CET 2009

iu2 <israelu <at>> writes:

> Hi,
> Having a file called, I would like to read it into a string,
> and then import from that string.
> That is instead of importing from the fie system, I wonder if it's
> possible to eval the text in the string and treat it as a module.
> For example
> with file('') as f: txt =
> string_import(txt, 'funcs')  # is string_import possible?
> to have now a module called funcs with the functions defined in

You can do something like this:

import types
import sys

mymodule = types.ModuleType("mymodule", "Optional Doc-String")

with file('') as f: 
    txt =
exec txt in globals(), mymodule.__dict__
sys.modules['mymodule'] = mymodule

Note that you shouldn't exec untrusted code.
You might also look at the __import__ funciton, which can import by python path.
You might also look at the imp module.


More information about the Python-list mailing list