RestrictedPython

8.1 · active · verified Sat Apr 11

RestrictedPython is a tool that defines a subset of the Python language, allowing program input to be executed within a trusted environment. It is not a full sandbox system but aids in establishing a controlled execution space for untrusted code. The current stable version is 8.1, released on 2025-10-19, and the project maintains an active release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates compiling and executing a simple Python function within a restricted environment. It uses `compile_restricted` to process the source code and `exec` with a modified `safe_globals` dictionary to control available built-ins and attributes. You can extend `restricted_globals` to whitelist specific functions or modules as needed for your application.

from RestrictedPython import compile_restricted
from RestrictedPython import safe_globals

source_code = """
def greet(name):
    return 'Hello, ' + str(name) + '!'
"""

# Prepare the global namespace for execution
# safe_globals includes __builtins__ with restricted functions/modules
restricted_globals = safe_globals.copy()
# Add any specific names or functions you want to allow in the restricted scope
restricted_globals['_getattr_'] = getattr # Example: allowing getattr in a restricted manner

loc = {}
try:
    # Compile the restricted code
    byte_code = compile_restricted(
        source_code,
        filename='<restricted_code>',
        mode='exec'
    )
    # Execute the compiled code within the restricted globals
    exec(byte_code, restricted_globals, loc)

    # Call the function from the restricted execution's local scope
    result = loc['greet']('World')
    print(result)

    # Example of forbidden operation (will raise error if policy is strict)
    # forbidden_code = "import os; os.listdir('/')"
    # forbidden_byte_code = compile_restricted(forbidden_code, '<forbidden>', 'exec')
    # exec(forbidden_byte_code, safe_globals, {})

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →