Skip to content

Instantly share code, notes, and snippets.

@mallipeddi
Created March 29, 2009 11:37
Show Gist options
  • Save mallipeddi/87364 to your computer and use it in GitHub Desktop.
Save mallipeddi/87364 to your computer and use it in GitHub Desktop.
An experiment with code-objects and namespaces.
"""
codeobjects.py
An experiment with code-objects and namespaces.
Inspired by Jeff Rush's PyCON'09 talk.
http://us.pycon.org/2009/conference/schedule/event/7/
Compiles a module at run-time from a string containing the code for the module
and installs a new module object in sys.modules ready to be importable!
"""
import types, sys
mod_code_str = """
x = 10
class Person(object):
def __init__(self):
pass
def foobar():
return "invoked foobar!"
"""
# compile the module's code into code-objects
# -> parses the code into a tree of code-objects
# -> returns the root of the tree (ie) code-object for the Module
mod_code = compile(mod_code_str, "<runtime>", "exec")
# create an instance of an empty Module object (let's call our module 'mymod')
mod = types.ModuleType('mymod', 'module created at run-time by parsing code from a string')
# exec module's code in the empty Module object's namespace
exec mod_code in mod.__dict__
# install the Module object into sys.module to make it `importable`
sys.modules['mymod'] = mod
# start using mymod!
import mymod
print mymod.x
print mymod.Person()
print mymod.foobar()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment