From fe7c038ca1b7541bc60817fe2c2c943b9c574742 Mon Sep 17 00:00:00 2001 From: Maximilien Cuony Date: Wed, 1 Oct 2025 13:53:19 +0200 Subject: [PATCH] Fix new coding style with multiple type choices and optionnal values --- src/implicitdict/__init__.py | 6 ++++-- src/implicitdict/jsonschema.py | 4 +++- tests/test_types.py | 4 ++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/implicitdict/__init__.py b/src/implicitdict/__init__.py index 0bad446..8768a22 100644 --- a/src/implicitdict/__init__.py +++ b/src/implicitdict/__init__.py @@ -210,7 +210,9 @@ def _parse_value(value, value_type: type): return result elif ( - (generic_type is Union or generic_type is UnionType) and len(arg_types) == 2 and arg_types[1] is type(None) + (generic_type is Union or generic_type is UnionType) + and len(arg_types) >= 2 + and any([arg_type is type(None) for arg_type in arg_types]) ): # Type is an Optional declaration if value is None: @@ -297,7 +299,7 @@ def _get_fields(subtype: type) -> tuple[set[str], set[str]]: optional_fields.add(key) elif generic_type is Union or generic_type is UnionType: generic_args = get_args(field_type) - if len(generic_args) == 2 and generic_args[1] is type(None): + if len(generic_args) >= 2 and any([arg_type is type(None) for arg_type in generic_args]): optional_fields.add(key) for key in attributes: if key not in annotations: diff --git a/src/implicitdict/jsonschema.py b/src/implicitdict/jsonschema.py index afdf9d3..7ada8ca 100644 --- a/src/implicitdict/jsonschema.py +++ b/src/implicitdict/jsonschema.py @@ -145,7 +145,9 @@ def _schema_for( return schema, False elif ( - (generic_type is Union or generic_type is UnionType) and len(arg_types) == 2 and arg_types[1] is type(None) + (generic_type is Union or generic_type is UnionType) + and len(arg_types) >= 2 + and any([arg_type is type(None) for arg_type in arg_types]) ): # Type is an Optional declaration subschema, _ = _schema_for(arg_types[0], schema_vars_resolver, schema_repository, context) diff --git a/tests/test_types.py b/tests/test_types.py index 422f612..a7b275e 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -110,6 +110,10 @@ class OptionalData(ImplicitDict): optional_field2_with_none_default: Optional[str] = None # noqa UP045 optional_field3_with_default: Optional[str] = "concrete default" # noqa UP045 new_style_optional: str | None + new_style_optional_2: str | bool | None + new_style_optional_3: str | None | bool + new_style_optional_4: None | str | bool + new_style_optional_5: str | list[str] | None | list[bool] | bool @staticmethod def example_values():