Replace Type with type
This commit is contained in:
parent
5188402be9
commit
58068c7b69
5 changed files with 25 additions and 26 deletions
|
@ -9,7 +9,6 @@ from typing import (
|
||||||
ClassVar,
|
ClassVar,
|
||||||
Collection,
|
Collection,
|
||||||
Mapping,
|
Mapping,
|
||||||
Type,
|
|
||||||
TypeVar,
|
TypeVar,
|
||||||
get_args,
|
get_args,
|
||||||
get_origin,
|
get_origin,
|
||||||
|
@ -39,7 +38,7 @@ class UnionSkip(Exception):
|
||||||
match their type."""
|
match their type."""
|
||||||
|
|
||||||
|
|
||||||
def handle_metadata(data_class: Type[Any], data: dict[str, Any]):
|
def handle_metadata(data_class: type[Any], data: dict[str, Any]):
|
||||||
"""Applies our custom metadata. Currently this just renames fields."""
|
"""Applies our custom metadata. Currently this just renames fields."""
|
||||||
# only transform a dict once, in case this is called multiple times
|
# only transform a dict once, in case this is called multiple times
|
||||||
data = data.copy()
|
data = data.copy()
|
||||||
|
@ -66,7 +65,7 @@ def handle_metadata(data_class: Type[Any], data: dict[str, Any]):
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
def handle_metadata_final(data_class: Type[Any], data: dict[str, Any]):
|
def handle_metadata_final(data_class: type[Any], data: dict[str, Any]):
|
||||||
"""As `handle_metadata`, but removes the key marking data as handled.
|
"""As `handle_metadata`, but removes the key marking data as handled.
|
||||||
|
|
||||||
Should only be used within a custom from_dict implementation.
|
Should only be used within a custom from_dict implementation.
|
||||||
|
@ -76,7 +75,7 @@ def handle_metadata_final(data_class: Type[Any], data: dict[str, Any]):
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
def _patched_build_value(type_: Type[Any], data: Any, config: Config) -> Any:
|
def _patched_build_value(type_: type[Any], data: Any, config: Config) -> Any:
|
||||||
if type_ not in config.type_hooks:
|
if type_ not in config.type_hooks:
|
||||||
origin = get_origin(type_)
|
origin = get_origin(type_)
|
||||||
if origin and origin in config.type_hooks:
|
if origin and origin in config.type_hooks:
|
||||||
|
@ -88,7 +87,7 @@ def _patched_build_value(type_: Type[Any], data: Any, config: Config) -> Any:
|
||||||
# workaround for https://github.com/konradhalas/dacite/issues/218
|
# workaround for https://github.com/konradhalas/dacite/issues/218
|
||||||
# this code is, like, really bad. but to be fair dacite's isn't a whole lot better
|
# this code is, like, really bad. but to be fair dacite's isn't a whole lot better
|
||||||
# and as long as it works, does it really matter?
|
# and as long as it works, does it really matter?
|
||||||
def _patched_build_value_for_union(union: Type[Any], data: Any, config: Config) -> Any:
|
def _patched_build_value_for_union(union: type[Any], data: Any, config: Config) -> Any:
|
||||||
types = extract_generic(union)
|
types = extract_generic(union)
|
||||||
if is_optional(union) and len(types) == 2:
|
if is_optional(union) and len(types) == 2:
|
||||||
return _patched_build_value(type_=types[0], data=data, config=config)
|
return _patched_build_value(type_=types[0], data=data, config=config)
|
||||||
|
@ -139,7 +138,7 @@ def _patched_build_value_for_union(union: Type[Any], data: Any, config: Config)
|
||||||
|
|
||||||
# fixes https://github.com/konradhalas/dacite/issues/217
|
# fixes https://github.com/konradhalas/dacite/issues/217
|
||||||
def _patched_build_value_for_collection(
|
def _patched_build_value_for_collection(
|
||||||
collection: Type[Any], data: Any, config: Config
|
collection: type[Any], data: Any, config: Config
|
||||||
) -> Any:
|
) -> Any:
|
||||||
data_type = data.__class__
|
data_type = data.__class__
|
||||||
if isinstance(data, Mapping) and is_subclass(collection, Mapping):
|
if isinstance(data, Mapping) and is_subclass(collection, Mapping):
|
||||||
|
@ -177,7 +176,7 @@ _T = TypeVar("_T")
|
||||||
|
|
||||||
|
|
||||||
def _patched_from_dict(
|
def _patched_from_dict(
|
||||||
data_class: Type[_T],
|
data_class: type[_T],
|
||||||
data: Data,
|
data: Data,
|
||||||
config: Config | None = None,
|
config: Config | None = None,
|
||||||
) -> _T:
|
) -> _T:
|
||||||
|
@ -198,7 +197,7 @@ def _patched_from_dict(
|
||||||
return _original_from_dict(data_class, data, config)
|
return _original_from_dict(data_class, data, config)
|
||||||
|
|
||||||
|
|
||||||
def _patched_is_valid_generic_class(value: Any, type_: Type[Any]) -> bool:
|
def _patched_is_valid_generic_class(value: Any, type_: type[Any]) -> bool:
|
||||||
origin = get_origin(type_)
|
origin = get_origin(type_)
|
||||||
if not (origin and isinstance(value, origin)):
|
if not (origin and isinstance(value, origin)):
|
||||||
return False
|
return False
|
||||||
|
|
|
@ -3,11 +3,11 @@
|
||||||
from common import dacite_patch as _ # isort: skip
|
from common import dacite_patch as _ # isort: skip
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import tomllib
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Callable, Type, TypeVar
|
from typing import Any, Callable, TypeVar
|
||||||
|
|
||||||
import tomllib
|
|
||||||
from dacite import Config, from_dict
|
from dacite import Config, from_dict
|
||||||
|
|
||||||
from common.dacite_patch import handle_metadata
|
from common.dacite_patch import handle_metadata
|
||||||
|
@ -20,7 +20,7 @@ _T_Dataclass = TypeVar("_T_Dataclass")
|
||||||
|
|
||||||
TypeHook = Callable[[_T_Dataclass | Any], _T_Dataclass | dict[str, Any]]
|
TypeHook = Callable[[_T_Dataclass | Any], _T_Dataclass | dict[str, Any]]
|
||||||
|
|
||||||
TypeHooks = dict[Type[_T_Dataclass], TypeHook[_T_Dataclass]]
|
TypeHooks = dict[type[_T_Dataclass], TypeHook[_T_Dataclass]]
|
||||||
|
|
||||||
TypeHookMaker = Callable[[_T_Input], TypeHooks[_T_Dataclass]]
|
TypeHookMaker = Callable[[_T_Input], TypeHooks[_T_Dataclass]]
|
||||||
|
|
||||||
|
@ -62,7 +62,7 @@ def load_json_object(path: Path) -> JSONDict:
|
||||||
|
|
||||||
|
|
||||||
def load_json_data(
|
def load_json_data(
|
||||||
data_class: Type[Any],
|
data_class: type[Any],
|
||||||
path: Path,
|
path: Path,
|
||||||
extra_data: dict[str, Any] = {},
|
extra_data: dict[str, Any] = {},
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
|
@ -71,14 +71,14 @@ def load_json_data(
|
||||||
return handle_metadata(data_class, data) | extra_data
|
return handle_metadata(data_class, data) | extra_data
|
||||||
|
|
||||||
|
|
||||||
def load_toml_data(data_class: Type[Any], path: Path) -> TOMLDict:
|
def load_toml_data(data_class: type[Any], path: Path) -> TOMLDict:
|
||||||
data = tomllib.loads(path.read_text("utf-8"))
|
data = tomllib.loads(path.read_text("utf-8"))
|
||||||
fill_placeholders(data)
|
fill_placeholders(data)
|
||||||
return handle_metadata(data_class, data)
|
return handle_metadata(data_class, data)
|
||||||
|
|
||||||
|
|
||||||
def from_dict_checked(
|
def from_dict_checked(
|
||||||
data_class: Type[_T_Dataclass],
|
data_class: type[_T_Dataclass],
|
||||||
data: dict[str, Any],
|
data: dict[str, Any],
|
||||||
config: TypedConfig,
|
config: TypedConfig,
|
||||||
path: Path | None = None,
|
path: Path | None = None,
|
||||||
|
|
|
@ -4,7 +4,7 @@ from __future__ import annotations
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from typing import Any, ClassVar, Self, Type
|
from typing import Any, ClassVar, Self
|
||||||
|
|
||||||
from dacite import StrictUnionMatchError, UnionMatchError, from_dict
|
from dacite import StrictUnionMatchError, UnionMatchError, from_dict
|
||||||
|
|
||||||
|
@ -14,7 +14,7 @@ from common.types import isinstance_or_raise
|
||||||
|
|
||||||
|
|
||||||
class WrongTag(UnionSkip):
|
class WrongTag(UnionSkip):
|
||||||
def __init__(self, union_type: Type[InternallyTaggedUnion], tag_value: str) -> None:
|
def __init__(self, union_type: type[InternallyTaggedUnion], tag_value: str) -> None:
|
||||||
super().__init__(
|
super().__init__(
|
||||||
f"Expected {union_type._tag_key}={union_type._expected_tag_value}, got {tag_value}"
|
f"Expected {union_type._tag_key}={union_type._expected_tag_value}, got {tag_value}"
|
||||||
)
|
)
|
||||||
|
@ -30,8 +30,8 @@ class InternallyTaggedUnion(ABC):
|
||||||
|
|
||||||
_tag_key: ClassVar[str | None] = None
|
_tag_key: ClassVar[str | None] = None
|
||||||
_expected_tag_value: ClassVar[str | None] = None
|
_expected_tag_value: ClassVar[str | None] = None
|
||||||
_all_union_types: ClassVar[list[Type[Self]]]
|
_all_union_types: ClassVar[list[type[Self]]]
|
||||||
_concrete_union_types: ClassVar[defaultdict[str, list[Type[Self]]]]
|
_concrete_union_types: ClassVar[defaultdict[str, list[type[Self]]]]
|
||||||
|
|
||||||
def __init_subclass__(cls, tag: str | None, value: str | None) -> None:
|
def __init_subclass__(cls, tag: str | None, value: str | None) -> None:
|
||||||
cls._tag_key = tag
|
cls._tag_key = tag
|
||||||
|
@ -48,8 +48,8 @@ class InternallyTaggedUnion(ABC):
|
||||||
base._concrete_union_types[value].append(cls)
|
base._concrete_union_types[value].append(cls)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _union_bases(cls) -> list[Type[InternallyTaggedUnion]]:
|
def _union_bases(cls) -> list[type[InternallyTaggedUnion]]:
|
||||||
union_bases: list[Type[InternallyTaggedUnion]] = []
|
union_bases: list[type[InternallyTaggedUnion]] = []
|
||||||
for base in cls.__bases__:
|
for base in cls.__bases__:
|
||||||
if (
|
if (
|
||||||
issubclass(base, InternallyTaggedUnion)
|
issubclass(base, InternallyTaggedUnion)
|
||||||
|
@ -83,7 +83,7 @@ class InternallyTaggedUnion(ABC):
|
||||||
|
|
||||||
# try all the types
|
# try all the types
|
||||||
exceptions: list[Exception] = []
|
exceptions: list[Exception] = []
|
||||||
union_matches: dict[Type[InternallyTaggedUnion], InternallyTaggedUnion] = {}
|
union_matches: dict[type[InternallyTaggedUnion], InternallyTaggedUnion] = {}
|
||||||
|
|
||||||
for inner_type in tag_types:
|
for inner_type in tag_types:
|
||||||
try:
|
try:
|
||||||
|
|
|
@ -2,7 +2,7 @@ from __future__ import annotations
|
||||||
|
|
||||||
import string
|
import string
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Any, Mapping, Protocol, Self, Type, TypeGuard, TypeVar, get_origin
|
from typing import Any, Mapping, Protocol, Self, TypeGuard, TypeVar, get_origin
|
||||||
|
|
||||||
JSONDict = dict[str, "JSONValue"]
|
JSONDict = dict[str, "JSONValue"]
|
||||||
|
|
||||||
|
@ -16,7 +16,7 @@ _DEFAULT_MESSAGE = "Expected any of {expected}, got {actual}: {value}"
|
||||||
# there may well be a better way to do this but i don't know what it is
|
# there may well be a better way to do this but i don't know what it is
|
||||||
def isinstance_or_raise(
|
def isinstance_or_raise(
|
||||||
val: Any,
|
val: Any,
|
||||||
class_or_tuple: Type[_T] | tuple[Type[_T], ...],
|
class_or_tuple: type[_T] | tuple[type[_T], ...],
|
||||||
message: str = _DEFAULT_MESSAGE,
|
message: str = _DEFAULT_MESSAGE,
|
||||||
) -> TypeGuard[_T]:
|
) -> TypeGuard[_T]:
|
||||||
"""Usage: `assert isinstance_or_raise(val, str)`
|
"""Usage: `assert isinstance_or_raise(val, str)`
|
||||||
|
|
|
@ -2,7 +2,7 @@ from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, ClassVar, Generic, Self, Type, TypeVar
|
from typing import Any, ClassVar, Generic, Self, TypeVar
|
||||||
|
|
||||||
from common.deserialize import (
|
from common.deserialize import (
|
||||||
TypedConfig,
|
TypedConfig,
|
||||||
|
@ -62,7 +62,7 @@ class BookState:
|
||||||
|
|
||||||
def add_stateful_unions(
|
def add_stateful_unions(
|
||||||
self,
|
self,
|
||||||
*unions: Type[StatefulInternallyTaggedUnion[Self]],
|
*unions: type[StatefulInternallyTaggedUnion[Self]],
|
||||||
):
|
):
|
||||||
for union in unions:
|
for union in unions:
|
||||||
self._type_hooks |= union.make_type_hooks(self) | {
|
self._type_hooks |= union.make_type_hooks(self) | {
|
||||||
|
@ -128,7 +128,7 @@ class StatefulInternallyTaggedUnion(
|
||||||
value=None,
|
value=None,
|
||||||
):
|
):
|
||||||
# set by InternallyTaggedUnion, but we need the type hint here
|
# set by InternallyTaggedUnion, but we need the type hint here
|
||||||
_all_union_types: ClassVar[list[Type[Self]]]
|
_all_union_types: ClassVar[list[type[Self]]]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def resolve_union_with_state(
|
def resolve_union_with_state(
|
||||||
|
|
Loading…
Reference in a new issue