Skip to content

Commit 6e8d5da

Browse files
committed
Inline functions where possible
1 parent 06c1926 commit 6e8d5da

File tree

1 file changed

+13
-16
lines changed

1 file changed

+13
-16
lines changed

src/betterproto/__init__.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -336,16 +336,15 @@ def from_string(cls, name: str) -> "Enum":
336336
raise ValueError(f"Unknown value {name} for enum {cls.__name__}") from e
337337

338338

339-
def _pack_fmt(proto_type: str) -> str:
340-
"""Returns a little-endian format string for reading/writing binary."""
341-
return {
342-
TYPE_DOUBLE: "<d",
343-
TYPE_FLOAT: "<f",
344-
TYPE_FIXED32: "<I",
345-
TYPE_FIXED64: "<Q",
346-
TYPE_SFIXED32: "<i",
347-
TYPE_SFIXED64: "<q",
348-
}[proto_type]
339+
_pack_fmt: Callable[[str], struct.Struct] = {
340+
TYPE_DOUBLE: struct.Struct("<d"),
341+
TYPE_FLOAT: struct.Struct("<f"),
342+
TYPE_FIXED32: struct.Struct("<I"),
343+
TYPE_FIXED64: struct.Struct("<Q"),
344+
TYPE_SFIXED32: struct.Struct("<i"),
345+
TYPE_SFIXED64: struct.Struct("<q"),
346+
}.__getitem__
347+
"""Returns a little-endian (un)packer for reading/writing binary."""
349348

350349

351350
def encode_varint(value: int) -> bytes:
@@ -379,7 +378,7 @@ def _preprocess_single(proto_type: str, wraps: str, value: Any) -> bytes:
379378
# Handle zig-zag encoding.
380379
return encode_varint(value << 1 if value >= 0 else (value << 1) ^ (~0))
381380
elif proto_type in FIXED_TYPES:
382-
return struct.pack(_pack_fmt(proto_type), value)
381+
return _pack_fmt(proto_type).pack(value)
383382
elif proto_type == TYPE_STRING:
384383
return value.encode("utf-8")
385384
elif proto_type == TYPE_MESSAGE:
@@ -658,8 +657,7 @@ def __post_init__(self) -> None:
658657
self.__dict__["_unknown_fields"] = b""
659658
self.__dict__["_group_current"] = group_current
660659

661-
def __raw_get(self, name: str) -> Any:
662-
return super().__getattribute__(name)
660+
__raw_get = object.__getattribute__
663661

664662
def __eq__(self, other) -> bool:
665663
if type(self) is not type(other):
@@ -705,7 +703,7 @@ def __getattribute__(self, name: str) -> Any:
705703
Lazily initialize default values to avoid infinite recursion for recursive
706704
message types
707705
"""
708-
value = super().__getattribute__(name)
706+
value = self.__raw_get(name)
709707
if value is not PLACEHOLDER:
710708
return value
711709

@@ -937,8 +935,7 @@ def _postprocess_single(
937935
# Booleans use a varint encoding, so convert it to true/false.
938936
value = value > 0
939937
elif wire_type in {WIRE_FIXED_32, WIRE_FIXED_64}:
940-
fmt = _pack_fmt(meta.proto_type)
941-
value = struct.unpack(fmt, value)[0]
938+
(value,) = _pack_fmt(meta.proto_type).unpack(value)
942939
elif wire_type == WIRE_LEN_DELIM:
943940
if meta.proto_type == TYPE_STRING:
944941
value = str(value, "utf-8")

0 commit comments

Comments
 (0)