Compare commits

..

No commits in common. "87acfb8ef4a912201123008814c026257e7398ce" and "2ba90fc2d248d551eb14f3a032ef7a01b4b4153b" have entirely different histories.

2 changed files with 35 additions and 34 deletions

View File

@ -14,18 +14,12 @@ import typing as t
from dataclasses import dataclass, is_dataclass
from datetime import date, datetime
from functools import lru_cache
from typing import Any, Dict, NamedTuple, Optional, Type, TypeVar, Union
from typing import Any, Dict, Optional, Tuple, Type, TypeVar, Union
from typing import get_args, get_origin, get_type_hints
from toot.utils import get_text
from toot.utils.datetime import parse_datetime
# Generic data class instance
T = TypeVar("T")
# A dict decoded from JSON
Data = Dict[str, Any]
@dataclass
class AccountField:
@ -82,7 +76,7 @@ class Account:
source: Optional[dict]
@staticmethod
def __toot_prepare__(obj: Data) -> Data:
def __toot_prepare__(obj: Dict) -> Dict:
# Pleroma has not yet converted last_status_at from datetime to date
# so trim it here so it doesn't break when converting to date.
# See: https://git.pleroma.social/pleroma/pleroma/-/issues/1470
@ -272,7 +266,7 @@ class Status:
return self.reblog or self
@staticmethod
def __toot_prepare__(obj: Data) -> Data:
def __toot_prepare__(obj: Dict) -> Dict:
# Pleroma has a bug where created_at is set to an empty string.
# To avoid marking created_at as optional, which would require work
# because we count on it always existing, set it to current datetime.
@ -463,25 +457,27 @@ class List:
# see: https://git.pleroma.social/pleroma/pleroma/-/issues/2918
replies_policy: Optional[str]
# ------------------------------------------------------------------------------
class Field(NamedTuple):
name: str
type: Any
default: Any
# Generic data class instance
T = TypeVar("T")
class ConversionError(Exception):
"""Raised when conversion fails from JSON value to data class field."""
def __init__(self, data_class: type, field: Field, field_value: Optional[str]):
def __init__(
self,
data_class: Type,
field_name: str,
field_type: Type,
field_value: Optional[str]
):
super().__init__(
f"Failed converting field `{data_class.__name__}.{field.name}` "
+ f"of type `{field.type.__name__}` from value {field_value!r}"
f"Failed converting field `{data_class.__name__}.{field_name}` "
+ f"of type `{field_type.__name__}` from value {field_value!r}"
)
def from_dict(cls: Type[T], data: Data) -> T:
def from_dict(cls: Type[T], data: Dict) -> T:
"""Convert a nested dict into an instance of `cls`."""
# Apply __toot_prepare__ if it exists
prepare = getattr(cls, '__toot_prepare__', None)
@ -489,19 +485,19 @@ def from_dict(cls: Type[T], data: Data) -> T:
data = prepare(data)
def _fields():
for field in _get_fields(cls):
value = data.get(field.name, field.default)
converted = _convert_with_error_handling(cls, field, value)
yield field.name, converted
for name, type, default in get_fields(cls):
value = data.get(name, default)
converted = _convert_with_error_handling(cls, name, type, value)
yield name, converted
return cls(**dict(_fields()))
@lru_cache
def _get_fields(cls: type) -> t.List[Field]:
@lru_cache(maxsize=100)
def get_fields(cls: Type) -> t.List[Tuple[str, Type, Any]]:
hints = get_type_hints(cls)
return [
Field(
(
field.name,
_prune_optional(hints[field.name]),
_get_default_value(field)
@ -510,11 +506,11 @@ def _get_fields(cls: type) -> t.List[Field]:
]
def from_dict_list(cls: Type[T], data: t.List[Data]) -> t.List[T]:
def from_dict_list(cls: Type[T], data: t.List[Dict]) -> t.List[T]:
return [from_dict(cls, x) for x in data]
def _get_default_value(field: dataclasses.Field):
def _get_default_value(field):
if field.default is not dataclasses.MISSING:
return field.default
@ -524,16 +520,21 @@ def _get_default_value(field: dataclasses.Field):
return None
def _convert_with_error_handling(data_class: type, field: Field, field_value: Any) -> Any:
def _convert_with_error_handling(
data_class: Type,
field_name: str,
field_type: Type,
field_value: Optional[str]
):
try:
return _convert(field.type, field_value)
return _convert(field_type, field_value)
except ConversionError:
raise
except Exception:
raise ConversionError(data_class, field, field_value)
raise ConversionError(data_class, field_name, field_type, field_value)
def _convert(field_type: Any, value: Any) -> Any:
def _convert(field_type, value):
if value is None:
return None
@ -556,7 +557,7 @@ def _convert(field_type: Any, value: Any) -> Any:
raise ValueError(f"Not implemented for type '{field_type}'")
def _prune_optional(field_type: type) -> type:
def _prune_optional(field_type: Type) -> Type:
"""For `Optional[<type>]` returns the encapsulated `<type>`."""
if get_origin(field_type) == Union:
args = get_args(field_type)

View File

@ -173,5 +173,5 @@ LANGUAGES = {
}
def language_name(code: str) -> str:
def language_name(code):
return LANGUAGES.get(code, code)