I need to create a unit-test like framework for light-weight auto grading of single-function python assignments. I'd love to do something like the following:
test = """
def foo(x):
return x * x
"""
compiled_module = magic_compile(test)
result = compiled_module.foo(3)
assert result == 9
Is there such a magic_compile function? The best I have so far is
exec(test)
result = getattr(sys.modules[__name__], 'foo')(3)
But this seems dangerous and unstable. This won't be run in production, so I'm not super-concerned about sandboxing and safety. Just wanted to make sure there wasn't a better solution I'm missing.
1 Answer 1
In Python 3.x:
module = {}
exec(test, module)
assert module['foo'](3) == 9
module isn't a real Python module, it's just a namespace to hold the code's globals to avoid polluting your module's namespace.
answered Nov 16, 2017 at 21:26
nneonneo
181k37 gold badges331 silver badges412 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
execing arbitrary code - you have to take the same precautions in both cases against malicious behaviour.