Bind compiled code to name?

Giuseppe Ottaviano giuott at
Mon Jun 23 06:58:25 CEST 2008

> class D:pass
> d = D()
> exec source_code in d.__dict__
> print d.some_name
> Notice that this will also give you d.__builtins__, which you might
> want to del afterwards.

If you want to mimic an import you can also do this:

import types
D = types.ModuleType('D')
exec source_code in D.__dict__
print D.some_name

This way D is a module (don't know if there are real differences with  
the class approach, though)

More information about the Python-list mailing list