sizmailov / pybind11-stubgen

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

`typing.Optional[T]` types converted to `T | None` #146

Closed VelocityRa closed 11 months ago

VelocityRa commented 11 months ago

This changed after the rewrite. Instead of keeping the Optional which feels the most idiomatic, Optional types (ie. my std::optional types via pybind11) are now converted to T | None.

sizmailov commented 11 months ago

Hi!

I prefer "pipe" syntax over typing.Union and typing.Optional. This choice might be subjective, as well as many others I made. Providing a CLI option for all of them would be tedious, error-prone, and nearly impossible to test all combinations.

I set the bar for the pybind11-stubgen CLI tool to satisfy the needs of ~90% of projects to a ~90% degree of perfection. If you want to go for the last 10% for your project, use pybind11_stubgen as a Python library and adjust it for your specific needs.

I plan to write a small customization guide, but it's not there yet. Essentially you need to write a copy of the __init__.py and assemble custom Parser, Printer, and Writer. As for the current issue, it would be necessary to customize only the Printer part, e.g.:

class MyPrinter(Printer):
    def print_type(self, type_: ResolvedType) -> str:
        if type_.parameters:
            param_str = (
                "["
                + ", ".join(self.print_annotation(p) for p in type_.parameters)
                + "]"
            )
        else:
            param_str = ""
        return f"{type_.name}{param_str}"

Hope that helps.

VelocityRa commented 11 months ago

Fair enough, thank you for the detailed reply!