Skip to content

Commit

Permalink
Fix typing issues
Browse files Browse the repository at this point in the history
  • Loading branch information
tlconnor committed Oct 14, 2024
1 parent 2f23b5c commit 60c70a2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 20 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ jobs:
- name: Run mypy
run: |
source venv/bin/activate
mypy hologram --ignore-missing-imports
mypy hologram --ignore-missing-imports --install-types --non-interactive
test:
runs-on: ubuntu-latest
Expand Down
38 changes: 19 additions & 19 deletions hologram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ def __init__(self, field: str, errors: Dict[str, Exception]):
super().__init__("generic validation error")
self.initialized = False

def late_initialize(self):
lines: List[str] = []
def late_initialize(self) -> None:
lines: list[str] = []
for name, exc in self.errors.items():
# do not use getattr(exc, 'message', str(exc)), it's slow!
if hasattr(exc, "message"):
Expand Down Expand Up @@ -217,11 +217,11 @@ def _validate_schema(h_schema_cls: Hashable) -> JsonDict:


# a restriction is a list of Field, str pairs
Restriction = List[Tuple[Field, str]]
Restriction = list[tuple[Field, str]]
# a restricted variant is a pair of an object that has fields with restrictions
# and those restrictions. Only JsonSchemaMixin subclasses may have restrictied
# fields.
Variant = Tuple[Type[T], Optional[Restriction]]
Variant = tuple[Type[T], Restriction | None]


def _get_restrictions(variant_type: Type) -> Restriction:
Expand All @@ -240,7 +240,7 @@ def _get_restrictions(variant_type: Type) -> Restriction:
return restrictions


def get_union_fields(field_type: Union[Any]) -> List[Variant]:
def get_union_fields(field_type: Union[Any]) -> list[Variant]:
"""
Unions have a __args__ that is all their variants (after typing's
type-collapsing magic has run, so caveat emptor...)
Expand Down Expand Up @@ -269,7 +269,7 @@ def get_union_fields(field_type: Union[Any]) -> List[Variant]:


def _encode_restrictions_met(
value: Any, restrict_fields: Optional[List[Tuple[Field, str]]]
value: Any, restrict_fields: list[tuple[Field, str]] | None
) -> bool:
if restrict_fields is None or len(restrict_fields) == 0:
return True
Expand All @@ -283,7 +283,7 @@ def _encode_restrictions_met(


def _decode_restrictions_met(
value: Any, restrict_fields: Optional[List[Tuple[Field, str]]]
value: Any, restrict_fields: list[tuple[Field, str]] | None
) -> bool:
if restrict_fields is None:
return True
Expand All @@ -307,25 +307,25 @@ class JsonSchemaMixin:
convert to and from JSON encodable dicts with validation against the schema
"""

_field_encoders: ClassVar[Dict[Type, FieldEncoder]] = {
_field_encoders: ClassVar[dict[Type, FieldEncoder]] = {
datetime: DateTimeFieldEncoder(),
UUID: UuidField(),
}

# Cache of the generated schema
_schema: ClassVar[Optional[Dict[str, CompleteSchema]]] = None
_schema: ClassVar[Optional[dict[str, CompleteSchema]]] = None

# Cache of field encode / decode functions
_encode_cache: ClassVar[Optional[Dict[Any, _ValueEncoder]]] = None
_decode_cache: ClassVar[Optional[Dict[Any, _ValueDecoder]]] = None
_mapped_fields: ClassVar[
Optional[Dict[Any, List[Tuple[Field, str]]]]
] = None
_encode_cache: ClassVar[dict[Any, _ValueEncoder] | None] = None
_decode_cache: ClassVar[dict[Any, _ValueDecoder] | None] = None
_mapped_fields: ClassVar[dict[Any, list[tuple[Field, str]]] | None] = (
None
)

ADDITIONAL_PROPERTIES: ClassVar[bool] = False

@classmethod
def field_mapping(cls) -> Dict[str, str]:
def field_mapping(cls) -> dict[str, str]:
"""Defines the mapping of python field names to JSON field names.
The main use-case is to allow JSON field names which are Python keywords
Expand Down Expand Up @@ -457,14 +457,14 @@ def encoder(_, v, __):
return encoder(field_type, value, omit_none)

@classmethod
def _get_fields(cls) -> List[Tuple[Field, str]]:
def _get_fields(cls) -> list[tuple[Field, str]]:
if cls._mapped_fields is None:
cls._mapped_fields = {}
if cls.__name__ not in cls._mapped_fields:
mapped_fields = []
type_hints = get_type_hints(cls)

for f in fields(cls):
for f in fields(cls): # type: ignore
# Skip internal fields
if f.name.startswith("_"):
continue
Expand Down Expand Up @@ -629,7 +629,7 @@ def _find_matching_validator(cls: Type[T], data: JsonDict) -> T:
for subclass in cls.__subclasses__():
try:
if is_dataclass(subclass):
return subclass.from_dict(data)
return subclass.from_dict(data) # type: ignore

except ValidationError:
continue
Expand Down Expand Up @@ -879,7 +879,7 @@ def all_json_schemas(cls) -> JsonDict:
definitions = {}
for subclass in cls.__subclasses__():
if is_dataclass(subclass):
definitions.update(subclass.json_schema(embeddable=True))
definitions.update(subclass.json_schema(embeddable=True)) # type: ignore
else:
definitions.update(subclass.all_json_schemas())
return definitions
Expand Down

0 comments on commit 60c70a2

Please sign in to comment.