Skip to content

Commit 29a71f6

Browse files
Bugfix for setting settings of Generic type
1 parent 9064e3e commit 29a71f6

2 files changed

Lines changed: 15 additions & 5 deletions

File tree

src/labthings_fastapi/properties.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -872,12 +872,20 @@ def model_to_value(self, value: BaseModel) -> Value:
872872
type.
873873
:raises TypeError: if the supplied value cannot be converted to the right type.
874874
"""
875-
if isinstance(value, self.value_type):
875+
# If it is a root model unrap the value
876+
value = value.root if isinstance(value, RootModel) else value
877+
try:
878+
if isinstance(value, self.value_type):
879+
return value
880+
except TypeError:
881+
# In the case that the self.value_type is a typing.GenericAlias or some
882+
# complicated associated type like typing._UnionGenericAlias then
883+
# isinstace itself with throw a TypeError.
884+
# Instead create root model for validation.
885+
ValidationModel = RootModel[self.value_type]
886+
# Use the model to validate the value before setting.
887+
ValidationModel(value)
876888
return value
877-
elif isinstance(value, RootModel):
878-
root = value.root
879-
if isinstance(root, self.value_type):
880-
return root
881889
msg = f"Model {value} isn't {self.value_type} or a RootModel wrapping it."
882890
raise TypeError(msg)
883891

src/labthings_fastapi/thing.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,8 @@ def load_settings(self) -> None:
237237
f"An extra key {name} was found in the settings file. "
238238
"It will be deleted the next time settings are saved."
239239
)
240+
except TypeError:
241+
self.logger.warning(f"Failed to load {name} with a TypeError.")
240242
except (
241243
FileNotFoundError,
242244
JSONDecodeError,

0 commit comments

Comments
 (0)