Skip to content

Commit 1c611fc

Browse files
committed
Workaround for cattrs<23.2.0
Signed-off-by: Cristian Le <[email protected]>
1 parent 1194b0b commit 1c611fc

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/scikit_build_core/file_api/_cattrs_converter.py

+18-1
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,21 @@
22

33
import builtins
44
import json
5+
from importlib.metadata import version
56
from pathlib import Path
6-
from typing import Any, Callable, Dict, Type, TypeVar # noqa: TID251
7+
from typing import Any, Callable, Dict, Type, TypeVar, Union # noqa: TID251
78

89
import cattr
910
import cattr.preconf.json
11+
from cattrs import ClassValidationError
12+
from packaging.version import Version
1013

14+
from .._compat.typing import get_args
1115
from .model.cache import Cache
1216
from .model.cmakefiles import CMakeFiles
1317
from .model.codemodel import CodeModel, Target
1418
from .model.codemodel import Directory as CodeModelDirectory
19+
from .model.common import Paths
1520
from .model.directory import Directory
1621
from .model.index import Index, Reply
1722

@@ -49,11 +54,23 @@ def from_json_file(with_path: Dict[str, Any], t: Type[T]) -> T:
4954
t = Directory # type: ignore[assignment]
5055
return converter.structure_attrs_fromdict(raw, t)
5156

57+
def from_union(obj: Dict[str, Any], t: Type[T]) -> T:
58+
for try_type in get_args(t):
59+
try:
60+
return converter.structure(obj, try_type) # type: ignore[no-any-return]
61+
except ClassValidationError: # noqa: PERF203
62+
continue
63+
msg = f"Could not convert {obj} into {t}"
64+
raise TypeError(msg)
65+
5266
converter.register_structure_hook(CodeModel, from_json_file)
5367
converter.register_structure_hook(Target, from_json_file)
5468
converter.register_structure_hook(Cache, from_json_file)
5569
converter.register_structure_hook(CMakeFiles, from_json_file)
5670
converter.register_structure_hook(CodeModelDirectory, from_json_file)
71+
# Workaround for cattrs < 23.2.0 not handling Union with dataclass properly
72+
if Version(version("cattrs")) < Version("23.2.0"):
73+
converter.register_structure_hook(Union[str, Paths], from_union)
5774
return converter
5875

5976

0 commit comments

Comments
 (0)