Skip to content

Commit c621a41

Browse files
author
Michael Johansen
committed
Disambiguate datetime and timedelta types when converting.
Signed-off-by: Michael Johansen <[email protected]>
1 parent 5ade5a6 commit c621a41

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

src/nipanel/_convert.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import logging
66
from collections.abc import Collection
7-
from typing import Any
7+
from typing import Any, Iterable
88

99
from google.protobuf import any_pb2
1010

@@ -102,7 +102,7 @@ def _get_best_matching_type(python_value: object) -> str:
102102
container_types.append(Collection.__name__)
103103

104104
best_matching_type = None
105-
candidates = [parent.__name__ for parent in underlying_parents]
105+
candidates = _get_candidate_strings(underlying_parents)
106106
for candidate in candidates:
107107
containers_str = ".".join(container_types)
108108
python_typename = f"{containers_str}.{candidate}" if containers_str else candidate
@@ -140,3 +140,21 @@ def is_supported_type(value: object) -> bool:
140140
return True
141141
except TypeError:
142142
return False
143+
144+
145+
def _get_candidate_strings(candidates: Iterable[type]) -> list[str]:
146+
names_to_disambiguate = [
147+
"datetime",
148+
"DateTime",
149+
"timedelta",
150+
"TimeDelta",
151+
]
152+
153+
candidate_names = []
154+
for candidate in candidates:
155+
if candidate.__name__ in names_to_disambiguate:
156+
candidate_names.append(f"{candidate.__module__}.{candidate.__name__}")
157+
else:
158+
candidate_names.append(candidate.__name__)
159+
160+
return candidate_names

src/nipanel/converters/builtin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ class DTDateTimeConverter(Converter[dt.datetime, timestamp_pb2.Timestamp]):
126126
@property
127127
def python_typename(self) -> str:
128128
"""The Python type that this converter handles."""
129-
return dt.datetime.__name__
129+
return f"{dt.datetime.__module__}.{dt.datetime.__name__}"
130130

131131
@property
132132
def protobuf_message(self) -> Type[timestamp_pb2.Timestamp]:

tests/unit/test_convert.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
(tests.types.MixinIntEnum.VALUE11, "int"),
5555
(tests.types.MyStrEnum.VALUE1, "str"),
5656
(tests.types.MixinStrEnum.VALUE11, "str"),
57-
(dt.datetime.now(), "datetime"),
57+
(dt.datetime.now(), "datetime.datetime"),
5858
([False, False], "Collection.bool"),
5959
([b"mystr", b"mystr"], "Collection.bytes"),
6060
([456.2, 1.0], "Collection.float"),

0 commit comments

Comments
 (0)