1

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.

thomas88wp
  • 2,381
  • 19
  • 31
  • Running an arbitrary function isn't any less dangerous than `exec`ing arbitrary code - you have to take the same precautions in both cases against malicious behaviour. – nneonneo Nov 16 '17 at 21:19
  • Yeah, I don't think there's an easy way to sandbox python [as in this answer](https://stackoverflow.com/a/3068475/816458). I guess my larger concern is how to load it into an object that I can call. – thomas88wp Nov 16 '17 at 21:23

1 Answers1

2

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.

nneonneo
  • 171,345
  • 36
  • 312
  • 383