How to call a python built-in function in c++ with pybind11

Question:

I am using pybind11 to call a python built-in function like range in c++ code. But I only found way to call a function in module like this:

py::object os = py::module::import("os");
py::object makedirs = os.attr("makedirs");
makedirs("/tmp/path/to/somewhere");

But a python built-in function like range needn’t import any modules, so how can I use pybind11 to call range in c++ code?

Asked By: lys

||

Answers:

You could fetch range from the globals dict.

Answered By: Botje

You can also import the builtins module which contains all the built-in python functions.

In your case it would be something like:

py::object builtins = py::module_::import("builtins");
py::object range = builtins.attr("range");
range(0, 10);
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.