Skip to content

Commit 5d6826e

Browse files
committed
Change some multi-elif statements to match/case
1 parent 2e21ed5 commit 5d6826e

File tree

3 files changed

+52
-59
lines changed

3 files changed

+52
-59
lines changed

sdmx/convert/pandas.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -432,19 +432,20 @@ def handle_datetime(self, value: Any) -> None:
432432
stacklevel=2,
433433
)
434434

435-
if isinstance(value, (str, common.DimensionComponent)):
436-
self.datetime_dimension = value # type: ignore [assignment]
437-
elif isinstance(value, dict):
438-
# Unpack a dict of 'advanced' arguments
439-
self.datetime_axis = value.pop("axis", self.datetime_axis)
440-
self.datetime_dimension = value.pop("dim", self.datetime_dimension)
441-
self.datetime_freq = value.pop("freq", self.datetime_freq)
442-
if len(value):
443-
raise ValueError(f"Unexpected datetime={tuple(sorted(value))!r}")
444-
elif isinstance(value, bool):
445-
self.datetime_axis = 0 if value else -1
446-
else:
447-
raise TypeError(f"PandasConverter(…, datetime={type(value)})")
435+
match value:
436+
case str() | common.DimensionComponent():
437+
self.datetime_dimension = value # type: ignore [assignment]
438+
case dict():
439+
# Unpack a dict of 'advanced' arguments
440+
self.datetime_axis = value.pop("axis", self.datetime_axis)
441+
self.datetime_dimension = value.pop("dim", self.datetime_dimension)
442+
self.datetime_freq = value.pop("freq", self.datetime_freq)
443+
if len(value):
444+
raise ValueError(f"Unexpected datetime={tuple(sorted(value))!r}")
445+
case bool():
446+
self.datetime_axis = 0 if value else -1
447+
case _:
448+
raise TypeError(f"PandasConverter(…, datetime={type(value)})")
448449

449450
def __post_init__(self, datetime: Any, rtype: str | None) -> None:
450451
"""Transform and validate arguments."""

sdmx/model/internationalstring.py

Lines changed: 25 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@
99
# Types that can be converted into InternationalString
1010
Convertible = str | Sequence | Mapping | Iterable[tuple[str, str]]
1111

12-
TInternationalString: TypeAlias = "InternationalString" | "Convertible"
13-
TInternationalStringInit = TInternationalString | None
12+
TInternationalString: TypeAlias = "InternationalString" | Convertible
1413

1514
# TODO read this from the environment, or use any value set in the SDMX-ML spec.
1615
# Currently set to 'en' because test_dsd.py expects it.
@@ -23,14 +22,14 @@
2322
class InternationalString:
2423
"""SDMX-IM InternationalString.
2524
26-
SDMX-IM LocalisedString is not implemented. Instead, the 'localizations' is a
27-
mapping where:
25+
SDMX-IM LocalisedString is not implemented. Instead, :attr:`localizations` is a
26+
mapping in which:
2827
2928
- keys correspond to the 'locale' property of LocalisedString.
3029
- values correspond to the 'label' property of LocalisedString.
3130
32-
When used as a type hint with pydantic, InternationalString fields can be assigned
33-
to in one of four ways::
31+
When :class:`InternationalStringDescriptor` is used as a dataclass field type, the
32+
field can be assigned in one of four ways::
3433
3534
@dataclass
3635
class Foo:
@@ -55,39 +54,32 @@ class Foo:
5554
5655
Only the first method preserves existing localizations; the latter three replace
5756
them.
58-
5957
"""
6058

6159
__slots__ = ("localizations",)
6260

6361
localizations: dict[str, str]
6462

65-
def __init__(self, value: "Convertible" | None = None, **kwargs):
63+
def __init__(self, value: "Convertible" | None = None, **kwargs) -> None:
6664
# Handle initial values according to type
67-
if value is None:
68-
# Keyword arguments → dict, possibly empty
69-
value = dict(kwargs)
70-
elif isinstance(value, str):
71-
# Bare string
72-
value = {DEFAULT_LOCALE: value}
73-
elif (
74-
isinstance(value, Sequence)
75-
and len(value) == 2
76-
and isinstance(value[0], str)
77-
):
78-
# 2-tuple of str is (locale, label)
79-
value = {value[0]: value[1]}
80-
elif isinstance(value, Mapping):
81-
# dict; use directly
82-
value = dict(value)
83-
else:
84-
try:
85-
# Iterable of 2-tuples
86-
value = { # type: ignore [misc]
87-
locale: label for (locale, label) in value
88-
}
89-
except Exception:
90-
raise ValueError(value, kwargs)
65+
match value:
66+
case None: # Keyword arguments → dict, possibly empty
67+
value = dict(kwargs)
68+
case str(): # Bare string
69+
value = {DEFAULT_LOCALE: value}
70+
case Sequence() if len(value) == 2 and isinstance(value[0], str):
71+
# 2-tuple of str is (locale, label)
72+
value = {value[0]: value[1]}
73+
case Mapping(): # dict or similar; use directly
74+
value = dict(value)
75+
case _:
76+
try:
77+
# Iterable of 2-tuples
78+
value = { # type: ignore [misc]
79+
locale: label for (locale, label) in value
80+
}
81+
except Exception:
82+
raise ValueError(value, kwargs)
9183

9284
self.localizations = value
9385

@@ -149,7 +141,7 @@ def __get__(self, obj, type) -> InternationalString:
149141

150142
return obj.__dict__[self._name]
151143

152-
def __set__(self, obj, value: "TInternationalStringInit"):
144+
def __set__(self, obj, value: TInternationalString | None) -> None:
153145
if not isinstance(value, InternationalString):
154146
value = InternationalString(value)
155147
setattr(obj, self._name, value)

sdmx/reader/xml/v21.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,19 +1157,19 @@ def _obs(reader, elem):
11571157
args = dict()
11581158

11591159
for e in elem.iterchildren():
1160-
localname = QName(e).localname
1161-
if localname == "Attributes":
1162-
args["attached_attribute"] = reader.pop_single("Attributes")
1163-
elif localname == "ObsDimension":
1164-
# Mutually exclusive with ObsKey
1165-
args["dimension"] = dsd.make_key(
1166-
common.Key, {dim_at_obs.id: e.attrib["value"]}
1167-
)
1168-
elif localname == "ObsKey":
1169-
# Mutually exclusive with ObsDimension
1170-
args["dimension"] = reader.pop_single(common.Key)
1171-
elif localname == "ObsValue":
1172-
args["value"] = e.attrib["value"]
1160+
match QName(e).localname:
1161+
case "Attributes":
1162+
args["attached_attribute"] = reader.pop_single("Attributes")
1163+
case "ObsDimension":
1164+
# Mutually exclusive with ObsKey
1165+
args["dimension"] = dsd.make_key(
1166+
common.Key, {dim_at_obs.id: e.attrib["value"]}
1167+
)
1168+
case "ObsKey":
1169+
# Mutually exclusive with ObsDimension
1170+
args["dimension"] = reader.pop_single(common.Key)
1171+
case "ObsValue":
1172+
args["value"] = e.attrib["value"]
11731173

11741174
return reader.model.Observation(**args)
11751175

0 commit comments

Comments
 (0)