Skip to content

docstring type hint incorrect for argument depending on class declaration order #2263

Closed
@ixje

Description

@ixje

Issue description

The generated type-hint for the argument in the initialiser of class B (see below) is invalid and shows the internal namespace instead of the module. Output of main.py (again see below)

__init__(...)
    __init__(self: cmake_example.B, arg0: testns::A) -> None

Note that the code is functional (although useless). To get the correct type hints we have to define py::class_<A>(m, "A") before py::class_<B>(m, "B")

__init__(...)
    __init__(self: cmake_example.B, arg0: cmake_example.A) -> None

expected behaviour
I'd expected to see type hints resolved correctly, regardless of class declaration order.

Reproducible example code

cmakelists.txt

cmake_minimum_required(VERSION 2.8.12)
project(cmake_example)

set(PYTHON_EXECUTABLE ${CMAKE_CURRENT_SOURCE_DIR}/venv/bin/python3)

include(FetchContent)
FetchContent_Declare(
        pybind11
        GIT_REPOSITORY https://github.com/pybind/pybind11.git
        GIT_TAG        v2.5.0
)
FetchContent_MakeAvailable(pybind11)
pybind11_add_module(cmake_example src/main.cpp)

main.cpp

#include <pybind11/pybind11.h>

namespace py = pybind11;
namespace testns {
    class A {
        A() =default;
    };

    class B {
    public:
        B(A* a) {}
    };
};

using namespace testns;


PYBIND11_MODULE(cmake_example, m) {
    py::class_<B>(m, "B")
            .def(py::init([](A* a) {
                return B(a);
            }));

    py::class_<A>(m, "A")
            .def(py::init());
}

main.py

import cmake_example

if __name__ == '__main__':
    print(help(cmake_example.B.__init__))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions