Below is a practical recipe that satisfies both new constraints:
• the embedded Python interpreter is not allowed to define or instantiate user classes
• the same interpreter is fully debuggable / step-able from a host-side debugger
The solution is split into two parts:
────────────────────────────────────────
- Restricting the language
────────────────────────────────────────
Python’s built-in
__builtins__ dictionary is the gateway to every dangerous primitive.
By replacing it with a custom, stripped-down builtins module we can:
• remove the class statement (done by deleting __build_class__)
• remove metaclass machinery (type, object, __import__, etc.)
• keep only the tiny subset you want scripts to use
Minimal C++ snippet (pybind11 used for brevity):
#include <pybind11/embed.h>
namespace py = pybind11;
py::scoped_interpreter guard{};
// 1. Create a clean dict that will become the script globals
py::dict safe_globals;
safe_globals["__builtins__"] = py::module_::import("builtins");
// 2. Remove everything that makes classes possible
py::dict builtins = safe_globals["__builtins__"];
builtins.attr("pop")("__build_class__"); // kills 'class' keyword
builtins.attr("pop")("type");
builtins.attr("pop")("object");
builtins.attr("pop")("__import__"); // optional: block dynamic imports
// 3. Optionally inject only the symbols you want
safe_globals["detect_faces"] = py::cpp_function([](py::array_t<uint8_t> img){ ... });
// 4. Run user code
py::exec(R"(
# This will raise SyntaxError: invalid syntax
# class Foo: pass
result = detect_faces(my_frame)
)", safe_globals);
Result: any attempt to use class or type() raises SyntaxError/NameError.
────────────────────────────────────────
2. Making it debuggable / step-able
────────────────────────────────────────
The stock CPython you embed already supports remote debugging via the Debug Adapter Protocol (DAP).
Two mainstream options:
A. debugpy (Microsoft’s official DAP server)
• One-line insertion into the embedded interpreter
• Works with VS Code, PyCharm, Vim-DAP, etc.
// After Py_Initialize() but before running user code:
py::module_::import("debugpy").attr("listen")(5678); // default port
py::module_::import("debugpy").attr("wait_for_client")();
Attach VS Code with a "attach" launch configuration: