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

539 views Asked by At

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?

2

There are 2 answers

0
Botje On BEST ANSWER

You could fetch range from the globals dict.

0
Yaroslav Biloshytskyi On

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);