Skip to content

Commit

Permalink
Add one-of match example to README (#558)
Browse files Browse the repository at this point in the history
Removed the parts of the example that showed accessing an unset value, as it now raises an `AttributeError`, and added an example of the `match` way of accessing the attributes.

Related to #510 and #358.
  • Loading branch information
MicaelJarniac authored Mar 19, 2024
1 parent 5666393 commit dbd3192
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,22 @@ message Test {
}
```

You can use `betterproto.which_one_of(message, group_name)` to determine which of the fields was set. It returns a tuple of the field name and value, or a blank string and `None` if unset.
On Python 3.10 and later, you can use a `match` statement to access the provided one-of field, which supports type-checking:

```py
test = Test()
match test:
case Test(on=value):
print(value) # value: bool
case Test(count=value):
print(value) # value: int
case Test(name=value):
print(value) # value: str
case _:
print("No value provided")
```

You can also use `betterproto.which_one_of(message, group_name)` to determine which of the fields was set. It returns a tuple of the field name and value, or a blank string and `None` if unset.

```py
>>> test = Test()
Expand All @@ -292,17 +307,11 @@ You can use `betterproto.which_one_of(message, group_name)` to determine which o
>>> test.count = 57
>>> betterproto.which_one_of(test, "foo")
["count", 57]
>>> test.on
False

# Default (zero) values also work.
>>> test.name = ""
>>> betterproto.which_one_of(test, "foo")
["name", ""]
>>> test.count
0
>>> test.on
False
```

Again this is a little different than the official Google code generator:
Expand Down

0 comments on commit dbd3192

Please sign in to comment.