Skip to content

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

Open
@markuspi

Description

@markuspi

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions