Skip to content

Commit dbd3192

Browse files
Add one-of match example to README (#558)
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.
1 parent 5666393 commit dbd3192

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

README.md

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,22 @@ message Test {
277277
}
278278
```
279279

280-
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.
280+
On Python 3.10 and later, you can use a `match` statement to access the provided one-of field, which supports type-checking:
281+
282+
```py
283+
test = Test()
284+
match test:
285+
case Test(on=value):
286+
print(value) # value: bool
287+
case Test(count=value):
288+
print(value) # value: int
289+
case Test(name=value):
290+
print(value) # value: str
291+
case _:
292+
print("No value provided")
293+
```
294+
295+
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.
281296

282297
```py
283298
>>> test = Test()
@@ -292,17 +307,11 @@ You can use `betterproto.which_one_of(message, group_name)` to determine which o
292307
>>> test.count = 57
293308
>>> betterproto.which_one_of(test, "foo")
294309
["count", 57]
295-
>>> test.on
296-
False
297310

298311
# Default (zero) values also work.
299312
>>> test.name = ""
300313
>>> betterproto.which_one_of(test, "foo")
301314
["name", ""]
302-
>>> test.count
303-
0
304-
>>> test.on
305-
False
306315
```
307316

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

0 commit comments

Comments
 (0)