Markyroson
Markyroson

Reputation: 109

Using built-in "open" python method in pybind11 (C++)?

How do you use basic ("default"/"built-in"; don't need to be imported) python methods in pybind11?

Lists, dictionaries, and some others do have built-in compatibility, but the method I am looking specifically for (open) is not included via an import. I know that a way around it would be to create a python file with a method wrapping "open" and then calling it as you would any imported method, but I would prefer to do it directly in C++ (using pybind) if possible as otherwise that semi-defeats the purpose.

Any assistance/advice would be greatly appreciated.

Upvotes: 2

Views: 1003

Answers (1)

Roman Miroshnychenko
Roman Miroshnychenko

Reputation: 1564

You are wrong. First, built-in names are importable from builtins module (in Python 3):

py::object open = py::module::import("builtins").attr("open");

Second, open also lives in io module so you can also use the following line that is equivalent to the line above:

py::object open = py::module::import("io").attr("open");

This is for Python 3, but the last line works for Python 2.7 too.

Upvotes: 4

Related Questions