Search code examples
pythonc++pybind11

How to import basic functions like len() or help() in C++ with pybind11


I'm quite new to pybind11 and I was trying to import/borrow simple Python functions like len() or especially help() inside my C++ code.

Note that I don't want to use pybinds.doc() inside C++ since I want to extract names and types of the parameters passed to Python functions.

I'm already familiar with:

auto fnc = py::reinterpret_borrow< py::function >( 
    py::module::import( "sys" ).attr( "path" ).attr( "append" ) );

But I can't find any definition of how to import functions outside of specific python modules.


Solution

  • Thanks to @unddoch for mentioning the buitlins module.

    Unfortunately help() is using sys.stdout by default. Therefore I switched to using pydoc.render_doc() to catch it as a string.

    My working code looks like this:

    py::function helpFnc = py::reinterpret_borrow< py::function >(
        py::module::import( "pydoc" ).attr("render_doc") );
    auto helpResult = helpfunc(pyExecute,"%s",0,py::module::import( "pydoc" ).attr("plaintext"));
    
    std::cout << "Help in C++: " << helpResult.cast<std::string>() << std::endl;