Reputation: 1167
Say I have a Python package mymodule
based on a Pybind11 extension where the following code works like a charm after running python setup.py install
:
from mypackage.subA import foo # foo is written in C++.
from mypackage.subB import bar # Same for bar.
I now want to add some pure Python code in one of the submodules, say subA
, so that I can also do
from mypackage.subA import pure_python_func
I've made an MCVE of such a project to hopefully make this as clear as possible.
If I add a file mypackage/subA.py
in which I write pure_python_func
(and add an empty mypackage/__init__.py
), I can import the Python part, but the extension module disappears. I.e.
from mypackage.subA import pure_python_func # Works
from mypackage.subA import foo # Fails
from mypackage.subB import bar # Fails
My question is how can I end up with a something that has both extension code and Python code within the same package? Preferably within the same submodules, but at least within the same package. Any help is greatly appreciated!
Upvotes: 0
Views: 447
Reputation: 839
An easy way to do this is to build your C++ module into a protected module outside of your public module, and import this protected module into your public module.
For example, change mypackage.subA.foo
to build to _mypackage._foo
. Then the file mypackage/subA/__init__.py
would look something like this:
from _mypackage._foo import *
from mypackage.subA._pythonModule import *
# Any other python code could be imported here as well
Upvotes: 2