pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

feat(typing): allow annotate methods with `pos_only` when only have the `self` argument

Open XuehaiPan opened this issue 1 year ago • 0 comments

Description

This PR allows to annotate methods such as __repr__(self) to be positional-only. For example:

py::class_<MyClass>(mod, "MyClass")
.def("__repr__", &MyClass::ToString, py::pos_only());
.def("my_method_no_args", &MyClass::MyMethodNoArgs, py::pos_only());

will generate annotation:

class MyClass:
    def __repr__(self: MyClass, /) -> str: ...
    def my_method_no_args(self: MyClass, /) -> RType: ...

Previously, the compilation failed here:

https://github.com/pybind/pybind11/blob/af67e87393b0f867ccffc2702885eea12de063fc/include/pybind11/pybind11.h#L301-L308

Although there is an implicitly defined argument self not present by py::arg("self").

Suggested changelog entry:

- Allow annotate methods with ``py::pos_only`` when only have the ``self`` argument.
- Make arguments for auto-generated dunder methods positional-only.

XuehaiPan avatar Oct 09 '24 07:10 XuehaiPan