简体   繁体   中英

pybind11: How to organize pybind module under a namespace package

In the below example of the pybind tutorial, a dynamic library is build.

setup.py in https://github.com/pybind/python_example :

ext_modules = [
    Pybind11Extension("python_example",
        ["src/main.cpp"],
        ...
        ),
]

setup(
    ext_modules=ext_modules,
    ...
)

It can be imported like this:

import python_example

But this lives in the global namespace and I would like to organize it under a namepsace package like this:

import mypackage.python_example

It seems that regardless of where I put the main.cpp it will be always accessible under the global namespace. I am thinking of eg numpy, where everything is used as np.somefunction and never do I import from an other namespace.

One can add a namespace in front of the module name.

Pybind11Extension("mypackage.python_example",
    ["src/main.cpp"],
    ...
)

But the name in PYBIND11_MODULE should stay as it is.

PYBIND11_MODULE(python_example, m) {

This will add a folder during the build: mypackage/python_example.cpython-38-x86_64-linux-gnu.so

This way you can import it like this:

import mypackage.python_example

Thanks to Marc Gliss for his answer in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM