You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Raise AttributeError on attempts to access unset oneof fields
This commit modifies `Message.__getattribute__` to raise
`AttributeError` whenever an attempt is made to access an unset `oneof`
field. This provides several benefits over the current approach:
* There is no longer any risk of `betterproto` users accidentally
relying on values of unset fields.
* Pattern matching with `match/case` on messages containing `oneof`
groups is now supported. The following is now possible:
```
@dataclasses.dataclass(eq=Fals
8000
e, repr=False)
class Test(betterproto.Message):
x: int = betterproto.int32_field(1, group="g")
y: str = betterproto.string_field(2, group="g")
match Test(y="text"):
case Test(x=v):
print("x", v)
case Test(y=v):
print("y", v)
```
Before this commit the code above would output `x 0` instead of
`y text`, but now the output is `y text` as expected. The reason
this works is because an `AttributeError` in a `case` pattern does
not propagate and instead simply skips the `case`.
* We now have a type-checkable way to deconstruct `oneof`. When running
`mypy` for the snippet above `v` has type `int` in the first `case`
and type `str` in the second `case`. For versions of Python that do
not support `match/case` (before 3.10) it is now possbile to use
`try/except/else` blocks to achieve the same result:
```
t = Test(y="text")
try:
v0: int = t.x
except AttributeError:
v1: str = t.y # `oneof` contains `y`
else:
pass # `oneof` contains `x`
```
This is a breaking change.
0 commit comments