Skip to content

Commit 9bee34c

Browse files
authored
Enable instantiating class as string with default params (#134)
1 parent 54051f1 commit 9bee34c

2 files changed

Lines changed: 6 additions & 1 deletion

File tree

exca/helpers.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -381,10 +381,12 @@ def _inject_type_on_serialization(
381381
def _retrieve_type_on_deserialization(
382382
cls, value: tp.Any, handler: pydantic.ValidatorFunctionWrapHandler
383383
) -> "DiscriminatedModel":
384+
key = cls._exca_discriminator_key
385+
if isinstance(value, str):
386+
value = {key: value} # -> instantiate corresponding class with default params
384387
if isinstance(value, dict):
385388
# WARNING: we do not want to modify `value` which will come from the outer scope
386389
# WARNING2: `sub_cls(**modified_value)` will trigger a recursion, and thus we need to remove the config key
387-
key = cls._exca_discriminator_key
388390
value = value.copy()
389391
sub_cls_val = value.pop(key, None)
390392
if sub_cls_val is not None:

exca/test_helpers.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,9 @@ def test_discriminated_model() -> None:
121121
w = World(**kwargs)
122122
assert w.string == "other"
123123
kwargs["name"] = "World" # must accept key as well
124+
# instantiate with string
125+
model = Model(sub="World") # type: ignore
126+
assert isinstance(model.sub, World)
124127

125128

126129
def test_discriminated_model_errors() -> None:

0 commit comments

Comments
 (0)