{"record":{"id":"58d4370084d59a54","repo":"huggingface/smolagents","slug":"forbidden-call-to-dunder-function-func-name","errorCode":null,"errorMessage":"Forbidden call to dunder function: {func.__name__}","messagePattern":"Forbidden call to dunder function: (.+?)","errorType":"exception","errorClass":"InterpreterError","httpStatus":null,"severity":"error","filePath":"src/smolagents/local_python_executor.py","lineNumber":917,"sourceCode":"            return super(cls, instance)\n        else:\n            raise InterpreterError(\"super() takes at most 2 arguments\")\n    elif func_name == \"print\":\n        state[\"_print_outputs\"] += \" \".join(map(str, args)) + \"\\n\"\n        return None\n    else:  # Assume it's a callable object\n        if (inspect.getmodule(func) == builtins) and inspect.isbuiltin(func) and (func not in static_tools.values()):\n            raise InterpreterError(\n                f\"Invoking a builtin function that has not been explicitly added as a tool is not allowed ({func_name}).\"\n            )\n        if (\n            hasattr(func, \"__name__\")\n            and func.__name__.startswith(\"__\")\n            and func.__name__.endswith(\"__\")\n            and (func.__name__ not in static_tools)\n            and (func.__name__ not in ALLOWED_DUNDER_METHODS)\n        ):\n            raise InterpreterError(f\"Forbidden call to dunder function: {func.__name__}\")\n        return func(*args, **kwargs)\n\n\ndef evaluate_subscript(\n    subscript: ast.Subscript,\n    state: dict[str, Any],\n    static_tools: dict[str, Callable],\n    custom_tools: dict[str, Callable],\n    authorized_imports: list[str],\n) -> Any:\n    index = evaluate_ast(subscript.slice, state, static_tools, custom_tools, authorized_imports)\n    value = evaluate_ast(subscript.value, state, static_tools, custom_tools, authorized_imports)\n    try:\n        return value[index]\n    except (KeyError, IndexError, TypeError) as e:\n        error_message = f\"Could not index {value} with '{index}': {type(e).__name__}: {e}\"\n        if isinstance(index, str) and isinstance(value, Mapping):\n            close_matches = difflib.get_close_matches(index, list(value.keys()))","sourceCodeStart":899,"sourceCodeEnd":935,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/local_python_executor.py#L899-L935","documentation":"Calls to dunder (double-underscore) methods are forbidden unless the name appears in static_tools or the interpreter's ALLOWED_DUNDER_METHODS whitelist. This prevents sandbox escapes via tricks like obj.__class__.__bases__[0].__subclasses__() or .__reduce__().","triggerScenarios":"Writing an explicit call to a dunder: x.__len__(), obj.__getitem__(0), getattr-style access evaluated to __globals__ or __reduce__, or calling __init__ directly.","commonSituations":"Agent code or prompt-injected output tries to reach internals for a sandbox escape; using dunder-call style instead of syntax sugar (x[0] instead of x.__getitem__(0)); calling __init__ for manual re-initialization.","solutions":["Use the equivalent syntactic sugar (len(x), x[0], iter(x)) instead of calling the dunder","If a dunder legitimately must be callable, add its name to the tools/static_tools you configure","Avoid introspection chains like __class__/__subclasses__ in generated code"],"exampleFix":"# before\nitem = seq.__getitem__(0)\n# after\nitem = seq[0]","handlingStrategy":"fallback","validationCode":"# normalize generated code: replace dunder calls with syntax sugar\nimport re\ncode = re.sub(r'\\.__len__\\(\\)', '', code)\ncode = re.sub(r'(\\w+)\\.__getitem__\\(([^)]+)\\)', r'\\1[\\2]', code)","typeGuard":null,"tryCatchPattern":"try:\n    evaluate_python(code, ...)\nexcept InterpreterError as e:\n    if 'dunder' in str(e):\n        # rewrite the offending dunder call to sugar form and retry","preventionTips":["Use len(x), x[0], iter(x) instead of dunders","Treat dunder-call attempts in agent output as prompt-injection red flags","Add only genuinely needed dunders to ALLOWED_DUNDER_METHODS via tools"],"tags":["python-executor","sandbox","dunder","security","smolagents"],"backgroundTag":"sandboxed-dunder-call-blocked","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}