Skip to content

Commit 26be1f7

Browse files
author
Michael Johansen
committed
Refactor if/else statements to use a lookup.
Signed-off-by: Michael Johansen <[email protected]>
1 parent 8166f1c commit 26be1f7

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

src/nipanel/converters/protobuf_types.py

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@
99
from nipanel.converters import Converter
1010

1111
_AnyScalarType: TypeAlias = Union[bool, int, float, str]
12+
SCALAR_TYPE_TO_PB_ATTR_MAP = {
13+
bool: "bool_value",
14+
int: "int32_value",
15+
float: "double_value",
16+
str: "string_value",
17+
}
1218

1319

1420
class ScalarConverter(Converter[Scalar[_AnyScalarType], scalar_pb2.ScalarData]):
@@ -28,16 +34,11 @@ def to_protobuf_message(self, python_value: Scalar[_AnyScalarType]) -> scalar_pb
2834
"""Convert the Python Scalar to a protobuf scalar_pb2.ScalarData."""
2935
message = self.protobuf_message()
3036
message.units = python_value.units
31-
if isinstance(python_value.value, bool):
32-
message.bool_value = python_value.value
33-
elif isinstance(python_value.value, int):
34-
message.int32_value = python_value.value
35-
elif isinstance(python_value.value, float):
36-
message.double_value = python_value.value
37-
elif isinstance(python_value.value, str):
38-
message.string_value = python_value.value
39-
else:
37+
38+
value_attr = SCALAR_TYPE_TO_PB_ATTR_MAP.get(type(python_value.value), None)
39+
if not value_attr:
4040
raise TypeError(f"Unexpected type for python_value.value: {type(python_value.value)}")
41+
setattr(message, value_attr, python_value.value)
4142

4243
return message
4344

@@ -46,14 +47,9 @@ def to_python_value(self, protobuf_value: scalar_pb2.ScalarData) -> Scalar[_AnyS
4647
if protobuf_value.units is None:
4748
raise ValueError("protobuf.units cannot be None.")
4849

49-
pb_type = protobuf_value.WhichOneof("value")
50-
if pb_type == "bool_value":
51-
return Scalar(protobuf_value.bool_value, protobuf_value.units)
52-
elif pb_type == "int32_value":
53-
return Scalar(protobuf_value.int32_value, protobuf_value.units)
54-
elif pb_type == "double_value":
55-
return Scalar(protobuf_value.double_value, protobuf_value.units)
56-
elif pb_type == "string_value":
57-
return Scalar(protobuf_value.string_value, protobuf_value.units)
58-
else:
50+
pb_type = str(protobuf_value.WhichOneof("value"))
51+
if pb_type not in SCALAR_TYPE_TO_PB_ATTR_MAP.values():
5952
raise ValueError(f"Unexpected value for protobuf_value.WhichOneOf: {pb_type}")
53+
54+
value = getattr(protobuf_value, pb_type)
55+
return Scalar(value, protobuf_value.units)

0 commit comments

Comments
 (0)