8000 Get rid of __raw_get · Gobot1234/python-betterproto@c942fe1 · GitHub
[go: up one dir, main page]

Skip to content

Commit c942fe1

Browse files
committed
Get rid of __raw_get
1 parent fea05f2 commit c942fe1

File tree

1 file changed

+37
-38
lines changed

1 file changed

+37
-38
lines changed

src/betterproto/__init__.py

Lines changed: 37 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -487,7 +487,7 @@ def decode_varint(buffer: bytes, pos: int) -> Tuple[int, int]:
487487
"""
488488
result = 0
489489
shift = 0
490-
while 1:
490+
while True:
491491
b = buffer[pos]
492492
result |= (b & 0x7F) << shift
493493
pos += 1
@@ -629,6 +629,8 @@ class Message:
629629
Calls :meth:`__bool__`.
630630
"""
631631

632+
__slots__ = ("_serialized_on_wire", "_unknown_fields", "_group_current")
633+
632634
_serialized_on_wire: bool
633635
_unknown_fields: bytes
634636
_group_current: Dict[str, str]
@@ -644,8 +646,8 @@ def __post_init__(self) -> None:
644646
if meta.group:
645647
group_current.setdefault(meta.group)
646648

647-
value = self.__raw_get(field_name)
648-
if value != PLACEHOLDER and not (meta.optional and value is None):
649+
value = object.__getattribute__(self, field_name)
650+
if value is not PLACEHOLDER and not (meta.optional and value is None):
649651
# Found a non-sentinel value
650652
all_sentinel = False
651653

@@ -654,47 +656,42 @@ def __post_init__(self) -> None:
654656
group_current[meta.group] = field_name
655657

656658
# Now that all the defaults are set, reset it!
657-
self.__dict__["_serialized_on_wire"] = not all_sentinel
658-
self.__dict__["_unknown_fields"] = b""
659-
self.__dict__["_group_current"] = group_current
660-
661-
__raw_get = object.__getattribute__
659+
super().__setattr__("_serialized_on_wire", not all_sentinel)
660+
super().__setattr__("_unknown_fields", b"")
661+
super().__setattr__("_group_current", group_current)
662662

663663
def __eq__(self, other) -> bool:
664-
if type(self) is not type(other):
664+
if not isinstance(other, type(self)):
665665
return False
666666

667667
for field_name in self._betterproto.meta_by_field_name:
668-
self_val = self.__raw_get(field_name)
669-
other_val = other.__raw_get(field_name)
668+
self_val = object.__getattribute__(self, field_name)
669+
other_val = object.__getattribute__(other, field_name)
670670
if self_val is PLACEHOLDER:
671671
if other_val is PLACEHOLDER:
672672
continue
673673
self_val = self._get_field_default(field_name)
674674
elif other_val is PLACEHOLDER:
675675
other_val = other._get_field_default(field_name)
676676

677-
if self_val != other_val:
677+
if self_val != other_val and (
678+
not isinstance(self_val, float)
679+
or not isinstance(other_val, float)
680+
or not math.isnan(self_val)
681+
or not math.isnan(other_val)
682+
):
678683
# We consider two nan values to be the same for the
679684
# purposes of comparing messages (otherwise a message
680685
# is not equal to itself)
681-
if (
682-
isinstance(self_val, float)
683-
and isinstance(other_val, float)
684-
and math.isnan(self_val)
685-
and math.isnan(other_val)
686-
):
687-
continue
688-
else:
689-
return False
686+
return False
690687

691688
return True
692689

693690
def __repr__(self) -> str:
694691
parts = [
695692
f"{field_name}={value!r}"
696693
for field_name in self._betterproto.sorted_field_names
697-
for value in (self.__raw_get(field_name),)
694+
for value in (object.__getattribute__(self, field_name),)
698695
if value is not PLACEHOLDER
699696
]
700697
return f"{self.__class__.__name__}({', '.join(parts)})"
@@ -715,31 +712,33 @@ def __getattribute__(self, name: str) -> Any:
715712
def __setattr__(self, attr: str, value: Any) -> None:
716713
if attr != "_serialized_on_wire":
717714
# Track when a field has been set.
718-
self.__dict__["_serialized_on_wire"] = True
719-
720-
if hasattr(self, "_group_current"): # __post_init__ had already run
721-
if attr in self._betterproto.oneof_group_by_field:
722-
group = self._betterproto.oneof_group_by_field[attr]
723-
for field in self._betterproto.oneof_field_by_group[group]:
724-
if field.name == attr:
725-
self._group_current[group] = field.name
726-
else:
727-
super().__setattr__(field.name, PLACEHOLDER)
715+
super().__setattr__("_serialized_on_wire", True)
716+
717+
if (
718+
hasattr(self, "_group_current")
719+
and attr in self._betterproto.oneof_group_by_field
720+
): # __post_init__ had already run
721+
group = self._betterproto.oneof_group_by_field[attr]
722+
for field in self._betterproto.oneof_field_by_group[group]:
723+
if field.name == attr:
724+
self._group_current[group] = field.name
725+
else:
726+
super().__setattr__(field.name, PLACEHOLDER)
728727

729728
super().__setattr__(attr, value)
730729

731730
def __bool__(self) -> bool:
732731
"""True if the Message has any fields with non-default values."""
733732
return any(
734-
self.__raw_get(field_name)
733+
object.__getattribute__(self, field_name)
735734
not in (PLACEHOLDER, self._get_field_default(field_name))
736735
for field_name in self._betterproto.meta_by_field_name
737736
)
738737

739738
def __deepcopy__(self: T, _: Any = {}) -> T:
740739
kwargs = {}
741740
for name in self._betterproto.sorted_field_names:
742-
value = self.__raw_get(name)
741+
value = object.__getattribute__(self, name)
743742
if value is not PLACEHOLDER:
744743
kwargs[name] = deepcopy(value)
745744
return self.__class__(**kwargs) # type: ignore
@@ -879,9 +878,9 @@ def _type_hints(cls) -> Dict[str, Type]:
879878
def _cls_for(cls, field: dataclasses.Field, index: int = 0) -> Type:
880879
"""Get the message class for a field from the type hints."""
881880
field_cls = cls._type_hint(field.name)
882-
if hasattr(field_cls, "__args__") and index >= 0:
883-
if field_cls.__args__ is not None:
884-
field_cls = field_cls.__args__[index]
881+
args = getattr(field_cls, "__args__", None)
882+
if args and index >= 0 and args is not None:
883+
field_cls = field_cls.__args__[index]
885884
return field_cls
886885

887886
def _get_field_default(self, field_name: str) -> Any:
@@ -1325,7 +1324,7 @@ def is_set(self, name: str) -> bool:
13251324
:class:`bool`
13261325
`True` if field has been set, otherwise `False`.
13271326
"""
1328-
return self.__raw_get(name) is not PLACEHOLDER
1327+
return object.__getattribute__(self, name) is not PLACEHOLDER
13291328

13301329

13311330
def serialized_on_wire(message: Message) -> bool:

0 commit comments

Comments
 (0)
0