Add basic support for PEP 695 type parameters in functions#291
Add basic support for PEP 695 type parameters in functions#291gentlegiantJGC wants to merge 10 commits intopybind:mainfrom
Conversation
* Add support for basic PEP 695 type parameters in functions * Add tests * Reorder imports * Reformat * Reformat * Add stubs * Add exported names * Do not add typevar if name is a parameter If the name was given a a type parameter a TypeVar variable is not needed.
|
I think we should make this feature opt-in as a CLI switch as long as Python 3.9 and 3.11 have not reached their EOL. In many cases people want to generate a stub package that would cover all the Python versions they want to currently support. In this case, stubgen can act as linter, failing on parsing such docstrings if the flag is not passed. |
|
Why couldn't we use the Python version the stubs are built with to dictate what features are valid? I agree that this syntax should not appear in stubs generated by Python 3.11 and before. Ps. Python 3.9 has already reached end of life. |
I meant 3.10, sorry. The reason that pinning a specific Python version to produce a different syntax stub does not work is that it would require building version-specific wheels of a stub package for the end user. If we do not produce backwards compatible syntax (for the range of supported interpreter versions), regardless of which Python version stubgen is run on, I think this should be fixed too, unless such incompatibility cannot be avoided e.g. with typing_extensions |
|
I just want to clarify that the syntax I am adding support for is not automatically generated by pybind11. The library author needs to manually inject it into the docstring. It is down to them to ensure that this syntax only appears in libraries generated with python 3.12+. In older versions the syntax is invalid and stubgen should rightly error.
As you said, the stubs generated by pybind11 are aleady backwards incompatible.
The user only needs to build stubs with the oldest python version they support. If they want to support the new syntax they would need to build with newer python versions. |
|
I have fixed the code so that it does not generate the new syntax in versions prior to 3.12. I have also added tests for 3.10 and 3.11 just to show how the library outputs it. I also added an example to show how all versions can be correctly supported by the library author. |
PEP 695 added syntax for template arguments in classes, methods and functions.
Function example
This syntax is not generated by pybind11 but it can be added with custom type hints in a docstring like this.
py::options options; options.disable_function_signatures(); m.def( "passthrough1", [](py::object obj) { return obj; }, py::doc("passthrough1[T](obj: T) -> T\n")); options.enable_function_signatures();This pull requests adds basic support for this syntax.
It does not implement support for classes, variadics or constraints. I will leave this to someone who needs this.