pybind / pybind/pybind11

Include "object" as an argument type in the type signature of operator methods

Open
#2,269 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Issue description

Currently when declaring an operator method, the type signature in the docstring is not changed to include the additional type. In the example below we see the docstring:

__eq__(self: my_class.MyClass, arg0: my_class.MyClass) -> bool

however I would expect it to include the additional type signature that is more generic:

__eq__(*args, **kwargs)
Overloaded function.

1. __eq__(self: my_class.MyClass, arg0: my_class.MyClass) -> bool

2. __eq__(self: my_class.MyClass, arg0: object) -> NotImplemented

The use case where this is coming up:
I'm generating type stubs of a pybind module using stubgen. When running mypy with the generated stubs I see the following error:

Argument 1 of "__eq__" is incompatible with supertype "object"; supertype defines the argument type as "object"

Reproducible example code

# include <pybind11/pybind11.h>

namespace py = pybind11;

class MyClass
{
    MyClass(int id) : m_id(id);
    int m_id;
};

PYBIND11_MODULE(my_class, m) {
    py::class_<MyClass>(m, "MyClass")
        .def("__eq__",
            [](const MyClass& self, const MyClass& other) {
                return self.m_id == other.m_id;
            },
            py::is_operator()
        )
    ;
}
>>> import my_class
>>> my_class.MyClass.__eq__.__doc__
'__eq__(self: my_class.MyClass, arg0: my_class.MyClass) -> bool\n'

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing how py::is_operator affects operator signatures and how pybind11 assembles the generated doc text; then compare the behavior with the stubgen and mypy example in the issue. Done means an operator such as eq exposes both the concrete argument signature and the additional object signature returning NotImplemented.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
developer-experience, documentation
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.