From d245d2c249a53b158cb65115219b491ff4b95b1f Mon Sep 17 00:00:00 2001 From: Emily Wood Date: Tue, 16 Jul 2024 19:15:42 -0700 Subject: [PATCH] Clean up types in django_unicorn/ --- django_unicorn/cacher.py | 9 ++++++--- django_unicorn/call_method_parser.py | 8 ++++---- django_unicorn/serializer.py | 8 ++++---- django_unicorn/typer.py | 18 ++++++++++-------- django_unicorn/utils.py | 10 ++++++---- pyproject.toml | 12 ++++++++++++ 6 files changed, 42 insertions(+), 23 deletions(-) diff --git a/django_unicorn/cacher.py b/django_unicorn/cacher.py index 103eb9cb..b0a31441 100644 --- a/django_unicorn/cacher.py +++ b/django_unicorn/cacher.py @@ -1,6 +1,6 @@ import logging import pickle -from typing import List +from typing import Dict, List, Optional from django.core.cache import caches from django.http import HttpRequest @@ -28,7 +28,7 @@ class CacheableComponent: """ def __init__(self, component: "django_unicorn.views.UnicornView"): - self._state = {} + self._state: Dict = {} self.cacheable_component = component def __enter__(self): @@ -120,7 +120,10 @@ def cache_full_tree(component: "django_unicorn.views.UnicornView"): cache.set(_component.component_cache_key, _component) -def restore_from_cache(component_cache_key: str, request: HttpRequest = None) -> "django_unicorn.views.UnicornView": +def restore_from_cache( + component_cache_key: str, + request: Optional[HttpRequest] = None + ) -> "django_unicorn.views.UnicornView": """ Gets a cached unicorn view by key, restoring and getting cached parents and children and setting the request. diff --git a/django_unicorn/call_method_parser.py b/django_unicorn/call_method_parser.py index 6f8d0708..9bf9a33a 100644 --- a/django_unicorn/call_method_parser.py +++ b/django_unicorn/call_method_parser.py @@ -118,7 +118,7 @@ def parse_kwarg(kwarg: str, *, raise_if_unparseable=False) -> Dict[str, Any]: # context when the templatetag is rendered, so just return the expr # as a string. value = _get_expr_string(assign.value) - return {target.id: value} + return {target.id: value} #type: ignore else: raise InvalidKwargError(f"'{kwarg}' is invalid") except SyntaxError as e: @@ -128,7 +128,7 @@ def parse_kwarg(kwarg: str, *, raise_if_unparseable=False) -> Dict[str, Any]: @lru_cache(maxsize=128, typed=True) def parse_call_method_name( call_method_name: str, -) -> Tuple[str, Tuple[Any], Mapping[str, Any]]: +) -> Tuple[str, Tuple[Any, ...], Mapping[str, Any]]: """ Parses the method name from the request payload into a set of parameters to pass to a method. @@ -152,10 +152,10 @@ def parse_call_method_name( method_name = method_name[1:] tree = ast.parse(method_name, "eval") - statement = tree.body[0].value + statement = tree.body[0].value #type: ignore if tree.body and isinstance(statement, ast.Call): - call = tree.body[0].value + call = tree.body[0].value # type: ignore method_name = call.func.id args = [eval_value(arg) for arg in call.args] kwargs = {kw.arg: eval_value(kw.value) for kw in call.keywords} diff --git a/django_unicorn/serializer.py b/django_unicorn/serializer.py index c3648e54..e5499a91 100644 --- a/django_unicorn/serializer.py +++ b/django_unicorn/serializer.py @@ -29,7 +29,7 @@ try: from pydantic import BaseModel as PydanticBaseModel except ImportError: - PydanticBaseModel = None + PydanticBaseModel = None # type: ignore logger = logging.getLogger(__name__) @@ -188,7 +188,7 @@ def _get_model_dict(model: Model) -> dict: # Set `pk` for models that subclass another model which only have `id` set if not model_pk: - model_json["pk"] = model.pk or model.id + model_json["pk"] = model.pk or model.id #type: ignore # Add in m2m fields m2m_field_names = _get_many_to_many_field_related_names(model) @@ -235,7 +235,7 @@ def _json_serializer(obj): queryset_json.append(model_json) return queryset_json - elif PydanticBaseModel and isinstance(obj, PydanticBaseModel): + elif PydanticBaseModel and isinstance(obj, PydanticBaseModel): #type: ignore return obj.dict() elif isinstance(obj, Decimal): return str(obj) @@ -352,7 +352,7 @@ def _dumps( serialized_data: bytes, *, fix_floats: bool = True, - exclude_field_attributes: Optional[Tuple[str, ...]] = None, + exclude_field_attributes: Optional[Tuple[str]] = None, sort_dict: bool = True, ) -> Dict: """ diff --git a/django_unicorn/typer.py b/django_unicorn/typer.py index 8852dc2c..0ccd1ac8 100644 --- a/django_unicorn/typer.py +++ b/django_unicorn/typer.py @@ -2,7 +2,7 @@ from dataclasses import is_dataclass from datetime import date, datetime, time, timedelta, timezone from inspect import signature -from typing import Dict, List, Union +from typing import Any, Dict, List, Optional, Tuple, Union from typing import get_type_hints as typing_get_type_hints from uuid import UUID @@ -32,13 +32,15 @@ def _check_pydantic(cls) -> bool: # noqa: ARG001 from typing import get_args, get_origin except ImportError: # Fallback to dunder methods for older versions of Python - def get_args(type_hint): - if hasattr(type_hint, "__args__"): - return type_hint.__args__ - - def get_origin(type_hint): - if hasattr(type_hint, "__origin__"): - return type_hint.__origin__ + def get_args(tp: Any) -> Tuple[Any, ...]: + if hasattr(tp, "__args__"): + return tp.__args__ + return () + + def get_origin(tp: Any) -> Optional[Any]: + if hasattr(tp, "__origin__"): + return tp.__origin__ + return None try: diff --git a/django_unicorn/utils.py b/django_unicorn/utils.py index a673b909..a6816417 100644 --- a/django_unicorn/utils.py +++ b/django_unicorn/utils.py @@ -9,7 +9,7 @@ from django.conf import settings from django.template import engines from django.template.backends.django import Template -from django.utils.html import _json_script_escapes +from django.utils.html import _json_script_escapes # type: ignore from django.utils.safestring import SafeText, mark_safe try: @@ -33,13 +33,15 @@ def generate_checksum(data: Union[bytes, str, Dict]) -> str: The generated checksum. """ - data_bytes = data + data_bytes: Optional[bytes] = None - if isinstance(data, dict): + if isinstance(data, bytes): + data_bytes = data + elif isinstance(data, dict): data_bytes = str.encode(str(data)) elif isinstance(data, str): data_bytes = str.encode(data) - elif not isinstance(data, bytes): + else: raise TypeError(f"Invalid type: {type(data)}") checksum = hmac.new( diff --git a/pyproject.toml b/pyproject.toml index 51e0cc3f..5c7a55fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -162,6 +162,18 @@ ignore_missing_imports = true module="cachetools.*" ignore_missing_imports = true +[[tool.mypy.overrides]] +module = "django_unicorn.cacher" +disable_error_code = ["name-defined"] + +[[tool.mypy.overrides]] +module = "django_unicorn.typing" +disable_error_code = ["empty-body"] + +[[tool.mypy.overrides]] +module = "decorator" +ignore_missing_imports = true + [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api"