File size: 2,055 Bytes
0e02b97
 
7bd7366
0e02b97
 
 
 
 
 
 
 
 
 
 
 
bedb8e2
7bd7366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from __future__ import annotations

__all__ = ["add_two_numbers", "execute_python"]


def add_two_numbers(a: int, b: int) -> int:  # noqa: D401
    """Add two numbers together.

    Args:
        a (int): First number to add.
        b (int): Second number to add.

    Returns:
        int: The sum of the two numbers.
    """
    return a + b


def execute_python(code: str) -> str:
    """Execute Python code in a sandbox with a broader set of built-ins.

    The code is executed with restricted but useful built-ins and can import a
    small whitelist of standard library modules. Results should be stored in a
    variable named ``result`` or printed. The value of ``result`` is returned if
    present; otherwise any standard output captured during execution is
    returned.
    """
    import sys
    from io import StringIO

    allowed_modules = {"math", "random", "statistics"}

    def _safe_import(name: str, globals=None, locals=None, fromlist=(), level=0):
        if name in allowed_modules:
            return __import__(name, globals, locals, fromlist, level)
        raise ImportError(f"Import of '{name}' is not allowed")

    allowed_builtins = {
        "abs": abs,
        "min": min,
        "max": max,
        "sum": sum,
        "len": len,
        "range": range,
        "sorted": sorted,
        "enumerate": enumerate,
        "map": map,
        "filter": filter,
        "list": list,
        "dict": dict,
        "set": set,
        "tuple": tuple,
        "float": float,
        "int": int,
        "str": str,
        "bool": bool,
        "print": print,
        "__import__": _safe_import,
    }

    safe_globals: dict[str, object] = {"__builtins__": allowed_builtins}
    safe_locals: dict[str, object] = {}

    stdout = StringIO()
    original_stdout = sys.stdout
    try:
        sys.stdout = stdout
        exec(code, safe_globals, safe_locals)
    finally:
        sys.stdout = original_stdout

    if "result" in safe_locals:
        return str(safe_locals["result"])
    return stdout.getvalue().strip()