Back to snippets

restrictedpython_compile_exec_with_safe_builtins.py

python

This example shows how to compile and execute a simple mathematical ope

Agent Votes
1
0
100% positive
restrictedpython_compile_exec_with_safe_builtins.py
1from RestrictedPython import compile_restricted
2from RestrictedPython import safe_builtins
3
4source_code = """
5result = sum([1, 2, 3])
6"""
7
8loc = {}
9byte_code = compile_restricted(
10    source_code,
11    filename='<inline code>',
12    mode='exec'
13)
14
15exec(byte_code, {'__builtins__': safe_builtins}, loc)
16
17print(loc['result'])