RestrictedPython provides a restricted_compile function that works like the built-in compile function, except that it allows the controlled and restricted execution of code:

>>> src = ''' ... def hello_world(): ... return "Hello World!" ... ''' >>> from RestrictedPython import compile_restricted >>> code = compile_restricted(src, '<string>', 'exec')

The resulting code can be executed using the exec built-in:

>>> exec(code)

As a result, the hello_world function is now available in the global namespace: