Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add py::object casting example to embedding docs #2466

Merged
merged 5 commits into from
Sep 9, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions docs/advanced/embedding.rst
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,25 @@ The two approaches can also be combined:
std::cout << message;
}

Typically, a call to a function in a `py::module` returns a generic `py::object`,
which can often be autmatically cast to a specialized pybind11 type:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calling py::module::import returns a py::module.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's why I wrote "typically" 😉
But maybe that's not true either. Is it?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is true, at least from my reading:

static module import(const char *name) {

I think the "typically" can be dropped, because in C++, it is py::module (the C++ type itself).


.. code-block:: cpp

py::module os = py::module::import("os");
py::module path = py::module::import("os.path"); // like 'import os.path as path'
py::module np = py::module::import("numpy"); // like 'import numpy as np'

py::str curdir_abs = path.attr("abspath")(path.attr("curdir"));
py::print(py::str("Current directory: ") + curdir_abs);
py::dict environ = os.attr("environ");
py::print(environ["HOME"]);
py::array_t<float> arr = np.attr("ones")(3, "dtype"_a="float32");
py::print(py::repr(arr + py::int_(1)));

(Note that this example requires ``#include <pybind11/numpy.h>`` and
``using namespace pybind11::literals;`` to work.)

Importing modules
=================

Expand Down