Skip to content

Don't include cimports in generated stubs - #15

Closed
mdboom wants to merge 1 commit into
jon-edward:mainfrom
mdboom:filter-cimport
Closed

mdboom wants to merge 1 commit into
jon-edward:mainfrom
mdboom:filter-cimport

Conversation

@mdboom

@mdboom mdboom commented May 6, 2026

Copy link
Copy Markdown
Contributor

The current behavior of stubgen-pyx is to convert cimports to imports and include them in the .pyi file. The problem we are running into with this behavior is that most of what is cimported is not actually Python-exposed content, such as cdef struct or cdef functions etc. When these get included in the .pyi file and then we try to check for type annotation consistency using pyright or mypy, these imports fail (since they point to things that aren't Python importable and can't be re-exposed publicly). For our project, we would like to eventually get to something that is type check error-free, and this makes that challenging.

I realize this is a bit of a grey area for Cython. It is possible to cimport an extension type, which /is/ runtime imported and is exposed to Python. I think the only way for stubgen-pyx to tell the difference would be to actually resolve the cimport and see what it is.

I think it is better for users to use import for importing an extension type, which has (as far as I can tell) no behavioral difference, but makes it clear that the object is being imported for Python exposure.

There is more information in this part of the docs particularly:

It is important to understand that the cimport statement can only be used to import C data types, C functions and variables, and extension types. It cannot be used to import any Python objects, and (with one exception) it doesn’t imply any Python import at run time. If you want to refer to any Python names from a module that you have cimported, you will have to include a regular import statement for it as well.

The exception is that when you use cimport to import an extension type, its type object is imported at run time and made available by the name under which you imported it.

@mdboom

mdboom commented May 6, 2026

Copy link
Copy Markdown
Contributor Author

Closing this because I actually think the "trim imports" feature is doing this correctly already, I was just holding it wrong. And the post-trimming as already implemented doesn't have the downside of requiring user changes as this does. Sorry for the noise ;) Thanks for the great project!

@mdboom mdboom closed this May 6, 2026
@jon-edward

Copy link
Copy Markdown
Owner

No worries! Thank you for contributing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants