Bind compiled code to name?

"Martin v. Löwis" martin at
Sun Jun 22 20:33:14 CEST 2008

> If string `source_code` contains Python source code, how can I execute 
> that code, and bind it to some name? I tried compiling with: 
>     code_object = compile(source_code, 'errorfile', 'exec')
> but then what to do with `code_object`?
> P.S.
> If my intentions aren't that clear, this is what I'm trying to do. I want 
> to emulate this:
>    import some_module as some_name
> but with my code in `some_module` string, and not in file.

d = {}
exec source_code in d
some_name = d['some_name']


More information about the Python-list mailing list