Skip to content

Instantly share code, notes, and snippets.

@anandology
Last active December 15, 2015 04:59
Show Gist options
  • Save anandology/5205165 to your computer and use it in GitHub Desktop.
Save anandology/5205165 to your computer and use it in GitHub Desktop.
Example to demonstrate exec in Python
def run(init_code, code, wrapper, tests):
env = {}
exec(init_code, env)
runTests = env['runTests']
# Now all the variables and functions defined in init_code will be available in env
# replace the marker in wrapper. This will be done by erb template in pythonmonk
code2 = wrapper.replace("<%= user_code %>", code)
# execute the code in the same env, so that functions in init_code are available here
exec(code2, env)
exec(tests, env)
runTests()
init_code = """
def runTests():
# take all variables start with test_
tests = [v for k, v in globals().items() if k.startswith("test_")]
# simple test runner. We way want to use nosetests in production.
for t in tests:
try:
t()
except Exception, e:
print "FAIL", t.__doc__ or t.__name
print "error:", str(e)
else:
print "PASS", t.__doc__ or t.__name__
def square(x):
return x * x
"""
code = "square(3) + square(4)"
wrapper = "x = <%= user_code %>"
tests = """
def test_x():
"3 square + 4 square is 25."
assert x == 25, "expected 25, found %d" % x
def test_fail():
"just a failing test"
assert x == 20, "expected 20, found %d" % x
"""
run(init_code, code, wrapper, tests)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment