sizmailov / pybind11-stubgen

Generate stubs for python modules
Other
236 stars 47 forks source link

Option to translate pointers to `PointedType | None` #181

Closed VelocityRa closed 10 months ago

VelocityRa commented 11 months ago

Hello!

Usually in C++ code, pointers are assumed to be potentially nullptr (otherwise usually you'd use refs), but pybind11-stubgen translates a T*, to T, not T | None.

In my case I have a static constructor/factory method in a T class returning T*, which is nullptr if construction fails. I need to return a T* from it because I use virtual/polymorphism (the objects need to be the heap and it's not a particular derived one that's returned, it can be multiple ones). I could solely rely on throwing exceptions on failure but that's not always wanted.

It's not clear how to achieve this behavior without ugly boilerplate pybind11 wrappers for my constructor methods (ie. returning std::optional<T*> or std::variant<T*, py::none>), in every such instance.

This also applies to pointers as function arguments, not just return types.


Side-issue: This can also apply to any "nullable" type or more precisely, types with an std::nullptr_t constructor like std::function. I'd like a solution to this too if you can provide it, even if 'manual' by supplying a cmd arg (so preferably not requiring a fork). I run into this on my project on std::function default arg values of nullptr (which then results on annotation errors in IDEs). Let me know if I should open a new issue for that though.

Thanks for your time!

sizmailov commented 10 months ago

pybind11-stubgen deals with already built python modules and only analyses docstrings produced by pybind11. It's too late for pybind11-stubgen to fix the problem you describe, there is just no information at this point for stubgen.

You address this issue in the binding code, probably by using custom type casters.