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.
This commit is contained in:
parent
5666393f9d
commit
dbd31929d3
23
README.md
23
README.md
@ -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
|
```py
|
||||||
>>> test = Test()
|
>>> test = Test()
|
||||||
@ -292,17 +307,11 @@ You can use `betterproto.which_one_of(message, group_name)` to determine which o
|
|||||||
>>> test.count = 57
|
>>> test.count = 57
|
||||||
>>> betterproto.which_one_of(test, "foo")
|
>>> betterproto.which_one_of(test, "foo")
|
||||||
["count", 57]
|
["count", 57]
|
||||||
>>> test.on
|
|
||||||
False
|
|
||||||
|
|
||||||
# Default (zero) values also work.
|
# Default (zero) values also work.
|
||||||
>>> test.name = ""
|
>>> test.name = ""
|
||||||
>>> betterproto.which_one_of(test, "foo")
|
>>> betterproto.which_one_of(test, "foo")
|
||||||
["name", ""]
|
["name", ""]
|
||||||
>>> test.count
|
|
||||||
0
|
|
||||||
>>> test.on
|
|
||||||
False
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Again this is a little different than the official Google code generator:
|
Again this is a little different than the official Google code generator:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user