pybind / pybind/pybind11-stubgen

Incorrect type hints for custom classes named Sequence, Union, etc

Open
#241 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
361
Forks
75
PR merge metrics
No merged PRs in 30d

Description

Defining a custom pybind11 class that is named Sequence, Union, or other classes from the typing package leads to incorrectly generated signatures:

#include <pybind11/pybind11.h>
#include <pybind11/cast.h>

namespace py = pybind11;
using namespace pybind11::literals;

class Sequence {
  public:
  Sequence(int x) {}
};

PYBIND11_MODULE(sandbox, m)
{
  py::class_<Sequence>(m, "Sequence") //
    .def(py::init<int>(), "x"_a);
}

pybind11-stubgen incorrectly annotated the CTOR as self: typing.Sequence, x: int instead of self, x: int or at least self: Sequence, x: int

from __future__ import annotations
import typing
__all__ = ['Sequence']
class Sequence:
    def __init__(self: typing.Sequence, x: int) -> None:
        ...

Note that the original docstring __init__(self: sandbox.Sequence, x: int) contains the fully qualified class name, which would in theory allow more fine-grained differentiation between custom classes and classes from the standard library:

$ python -c "import sandbox; print(help(sandbox.Sequence))"

Help on class Sequence in module sandbox:

class Sequence(pybind11_builtins.pybind11_object)
 |  Method resolution order:
 |      Sequence
 |      pybind11_builtins.pybind11_object
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(...)
 |      __init__(self: sandbox.Sequence, x: int) -> None
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from pybind11_builtins.pybind11_object:
 |
 |  __new__(*args, **kwargs) class method of pybind11_builtins.pybind11_object
 |      Create and return a new object.  See help(type) for accurate signature.

Contributor guide

No contributing guide indexed for this repository

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

Reproduce the issue with the provided pybind11 C++ example and inspect how pybind11-stubgen converts constructor docstrings into type hints. The fix is correct handling of custom classes named like typing classes, producing an unqualified self or the custom Sequence type rather than typing.Sequence.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 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.