Replace Type with type

This commit is contained in:
object-Object 2023-06-26 19:35:50 -04:00
parent 5188402be9
commit 58068c7b69
5 changed files with 25 additions and 26 deletions

View file

@ -9,7 +9,6 @@ from typing import (
ClassVar,
Collection,
Mapping,
Type,
TypeVar,
get_args,
get_origin,
@ -39,7 +38,7 @@ class UnionSkip(Exception):
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."""
# only transform a dict once, in case this is called multiple times
data = data.copy()
@ -66,7 +65,7 @@ def handle_metadata(data_class: Type[Any], data: dict[str, Any]):
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.
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
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:
origin = get_origin(type_)
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
# 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?
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)
if is_optional(union) and len(types) == 2:
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
def _patched_build_value_for_collection(
collection: Type[Any], data: Any, config: Config
collection: type[Any], data: Any, config: Config
) -> Any:
data_type = data.__class__
if isinstance(data, Mapping) and is_subclass(collection, Mapping):
@ -177,7 +176,7 @@ _T = TypeVar("_T")
def _patched_from_dict(
data_class: Type[_T],
data_class: type[_T],
data: Data,
config: Config | None = None,
) -> _T:
@ -198,7 +197,7 @@ def _patched_from_dict(
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_)
if not (origin and isinstance(value, origin)):
return False

View file

@ -3,11 +3,11 @@
from common import dacite_patch as _ # isort: skip
import json
import tomllib
from dataclasses import dataclass, field
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 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]]
TypeHooks = dict[Type[_T_Dataclass], TypeHook[_T_Dataclass]]
TypeHooks = dict[type[_T_Dataclass], TypeHook[_T_Dataclass]]
TypeHookMaker = Callable[[_T_Input], TypeHooks[_T_Dataclass]]
@ -62,7 +62,7 @@ def load_json_object(path: Path) -> JSONDict:
def load_json_data(
data_class: Type[Any],
data_class: type[Any],
path: Path,
extra_data: dict[str, Any] = {},
) -> dict[str, Any]:
@ -71,14 +71,14 @@ def load_json_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"))
fill_placeholders(data)
return handle_metadata(data_class, data)
def from_dict_checked(
data_class: Type[_T_Dataclass],
data_class: type[_T_Dataclass],
data: dict[str, Any],
config: TypedConfig,
path: Path | None = None,

View file

@ -4,7 +4,7 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from collections import defaultdict
from typing import Any, ClassVar, Self, Type
from typing import Any, ClassVar, Self
from dacite import StrictUnionMatchError, UnionMatchError, from_dict
@ -14,7 +14,7 @@ from common.types import isinstance_or_raise
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__(
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
_expected_tag_value: ClassVar[str | None] = None
_all_union_types: ClassVar[list[Type[Self]]]
_concrete_union_types: ClassVar[defaultdict[str, list[Type[Self]]]]
_all_union_types: ClassVar[list[type[Self]]]
_concrete_union_types: ClassVar[defaultdict[str, list[type[Self]]]]
def __init_subclass__(cls, tag: str | None, value: str | None) -> None:
cls._tag_key = tag
@ -48,8 +48,8 @@ class InternallyTaggedUnion(ABC):
base._concrete_union_types[value].append(cls)
@classmethod
def _union_bases(cls) -> list[Type[InternallyTaggedUnion]]:
union_bases: list[Type[InternallyTaggedUnion]] = []
def _union_bases(cls) -> list[type[InternallyTaggedUnion]]:
union_bases: list[type[InternallyTaggedUnion]] = []
for base in cls.__bases__:
if (
issubclass(base, InternallyTaggedUnion)
@ -83,7 +83,7 @@ class InternallyTaggedUnion(ABC):
# try all the types
exceptions: list[Exception] = []
union_matches: dict[Type[InternallyTaggedUnion], InternallyTaggedUnion] = {}
union_matches: dict[type[InternallyTaggedUnion], InternallyTaggedUnion] = {}
for inner_type in tag_types:
try:

View file

@ -2,7 +2,7 @@ from __future__ import annotations
import string
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"]
@ -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
def isinstance_or_raise(
val: Any,
class_or_tuple: Type[_T] | tuple[Type[_T], ...],
class_or_tuple: type[_T] | tuple[type[_T], ...],
message: str = _DEFAULT_MESSAGE,
) -> TypeGuard[_T]:
"""Usage: `assert isinstance_or_raise(val, str)`

View file

@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
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 (
TypedConfig,
@ -62,7 +62,7 @@ class BookState:
def add_stateful_unions(
self,
*unions: Type[StatefulInternallyTaggedUnion[Self]],
*unions: type[StatefulInternallyTaggedUnion[Self]],
):
for union in unions:
self._type_hooks |= union.make_type_hooks(self) | {
@ -128,7 +128,7 @@ class StatefulInternallyTaggedUnion(
value=None,
):
# 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
def resolve_union_with_state(