This question is old but since it didn't contain an answer as I was looking into this issue I thought I'd provide what worked in my case.
I had a python module developed using the c-api with the following structure:
my_package/
├── docs
│ └── source
├── package_libs
│ ├── linux
│ └── win
│ ├── amd64
│ └── i386
├── package_src
│ ├── include
│ └── source
└── tests
the typegen command of the mypy package can generate stubs for packages pretty well.
The steps used were to first compile the package as you normally would with your existing setup.py for example.
Then generated the stubs for the generated .pyd or .so.
In my case the easiest was to install the whole package using pip for example and then calling stubgen on the whole module e.g:
pip install my_package
pip install mypy
stubgen my_package
This generates a my_package.pyi
file which can then be included in the package data of your setup.py
file as follows:
.
.
.
setup(
.
.
.
package=["my_package"],
package_data={"my_package": ["py.typed", "my_package.pyi", "__init__.pyi"]},
.
.
.
)
.
.
.
In there I include an empty py.typed
file to let utilities know that the package contains type stubs, the generated my_package.pyi
file and an __init__.pyi
file containing only the import of the stubs to make them available at the top level of my package as they are in module.
from my_package import *
This works for me and is reproducible even in CI environments where we generate the stubs before publishing the package so that they don't need to be manually updated or checked for discrepancy.
The final source repository looks like this with the added files :
my_package/
├── docs
│ └── source
├── my_package
│ ├── __init__.pyi
│ ├── my_package.pyi # generated by stubgen upon successful CI build in my case
│ └── py.typed
├── package_libs
│ ├── linux
│ └── win
│ ├── amd64
│ └── i386
├── package_src
│ ├── include
│ └── source
└── tests