_oneof.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # Copyright (c) 2025-2026 Buf Technologies, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import annotations
  15. from contextlib import suppress
  16. from typing import Final, Generic, TypeVar, final
  17. __all__ = ["Oneof"]
  18. C = TypeVar("C", bound=str)
  19. V = TypeVar("V")
  20. @final
  21. class Oneof(Generic[C, V]): # noqa: PLW1641
  22. """A oneof value with a field name and typed value.
  23. This class represents a oneof field value in protobuf messages. It combines
  24. a field name (the field name within the oneof) with its typed value, enabling
  25. type-safe pattern matching.
  26. Attributes:
  27. field: The name of the active oneof field
  28. value: The typed value for this field
  29. Examples:
  30. ```python
  31. a = Oneof(field="a", value="hello")
  32. match a:
  33. case Oneof(field="a", value=v):
  34. print(f"Got string: {v}")
  35. case Oneof(field="b", value=v):
  36. print(f"Got int: {v}")
  37. # Got string: hello
  38. ```
  39. """
  40. __slots__ = ("field", "value")
  41. __match_args__ = ("field", "value")
  42. field: Final[C]
  43. value: Final[V]
  44. def __init__(self, field: C, value: V) -> None:
  45. """Initializes a new Oneof.
  46. Args:
  47. field: The name of the active oneof field
  48. value: The typed value for this field
  49. """
  50. self.field = field
  51. self.value = value
  52. def __eq__(self, other: object) -> bool:
  53. if isinstance(other, Oneof):
  54. return self.field == other.field and self.value == other.value
  55. return False
  56. def __repr__(self) -> str:
  57. return f"Oneof(field={self.field!r}, value={self.value!r})"
  58. with suppress(ImportError):
  59. import protobuf_ext
  60. # Assigning to globals ensures docs / type checking pick up the rich Python type
  61. # while runtime uses the native implementation.
  62. globals()["Oneof"] = protobuf_ext.Oneof