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.

2
  • Running an arbitrary function isn't any less dangerous than execing arbitrary code - you have to take the same precautions in both cases against malicious behaviour. Commented Nov 16, 2017 at 21:19
  • Yeah, I don't think there's an easy way to sandbox python as in this answer. I guess my larger concern is how to load it into an object that I can call. Commented Nov 16, 2017 at 21:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.