sizmailov / pybind11-stubgen

Generate stubs for python modules
Other
228 stars 45 forks source link

Support default argument values #145

Closed VelocityRa closed 11 months ago

VelocityRa commented 11 months ago

It seems that default function/method argument/parameter values are not supported after the rewrite? They worked fine before.

pybind11 version: 2.10.3 pybind11-stubgen version: Was on 0.16.1 and recently updated to 2.1.

Are they supposed to work and I'm doing something wrong? Would appreciate any pointers. Thank you for your time!

sizmailov commented 11 months ago

Could you provide a minimal reproducible example?

VelocityRa commented 11 months ago

@sizmailov

C++/bindings:

PYBIND11_MODULE(test, m) {
    class Foo {
    public:
        Foo() = default;
        Foo(int x){}
    };
    py::class_<Foo>(m, "Foo")
        .def(py::init<>())
        .def(py::init<int>());

    class Bar {
    public:
        Bar(){};
        void test_int(int x = 5) {}
        void test_foo(Foo x = Foo()) {}
        void test_foo2(Foo x = Foo(5)) {}
    };
    py::class_<Bar>(m, "Bar")
        .def(py::init<>())
        .def("test_int", &Bar::test_int, py::arg("x") = 5)
        .def("test_foo", &Bar::test_foo, py::arg("x") = Foo())
        .def("test_foo2", &Bar::test_foo2, py::arg("x") = Foo(5));
}

Generated pyi:

from __future__ import annotations
import typing
__all__ = ['Bar', 'Foo']
class Bar:
    def __init__(self) -> None:
        ...
    def test_foo(self, x: Foo = ...) -> None:
        ...
    def test_foo2(self, x: Foo = ...) -> None:
        ...
    def test_int(self, x: int = ...) -> None:
        ...
class Foo:
    @typing.overload
    def __init__(self) -> None:
        ...
    @typing.overload
    def __init__(self, arg0: int) -> None:
        ...

docstring inside the module is fine:

>>> help(test.Bar.test_int)
Help on instancemethod in module test:

test_int(...)
    test_int(self: kit.Bar, x: int = 5) -> None

And on some other occasions (happens on my main project, would need to debug why), if an arg is of type ie. Type, the resulting pyi for some reason sets the type of the arg to Type | None (adds the | None) and does not even add the = ....

sizmailov commented 11 months ago

Thanks for the report and examples!

The default arguments parsing from docstings was not done properly in >=1.0. Should be fixed in #147.

And on some other occasions (happens on my main project, would need to debug why), if an arg is of type ie. Type, the resulting pyi for some reason sets the type of the arg to Type | None (adds the | None) and does not even add the = ....

It would be helpful if you could make minimal example to demonstrate the problem

VelocityRa commented 11 months ago

Thanks for the quick response! The fix works on my main project too, never mind about the None thing.