protobuf icon indicating copy to clipboard operation
protobuf copied to clipboard

Support python 3.10 optional syntax

Open peku33 opened this issue 6 months ago • 1 comments

Python 3.10 introduced str | None syntax which should be equivalent to Optional[str]. At the moment such syntax isn't properly recognized by pure_protobuf.

Following declaration will raise error:

@dataclass(kw_only=True)
class Bar(BaseMessage):
    foo: Annotated[str | None, Field(1)]

with

UnsupportedAnnotationError: type annotation `str | None` is not supported

This is because get_origin in pure_protobuf.helpers._typing.extract_optional checks for Union only, while this syntax has UnionType from types origin. The rest is the same.

This probably could be easily fixed by changing is comparison to in (Union, UnionType), however special care must be taken, because (same as NoneType) UnionType was introduced in 3.10.

Thank you.

peku33 avatar Jun 09 '25 20:06 peku33

Thank you for pointing it out! I've faced a very similar issue in another project, and you are correct that checking for UnionType is needed. I'll have a look; it should not be difficult to fix.

eigenein avatar Jun 09 '25 21:06 eigenein