Skip to content

Instantly share code, notes, and snippets.

@Tinche
Created August 6, 2022 17:46
Show Gist options
  • Save Tinche/ba3ece47874091945a95f15e7fe25096 to your computer and use it in GitHub Desktop.
Save Tinche/ba3ece47874091945a95f15e7fe25096 to your computer and use it in GitHub Desktop.
from typing import Any, Callable, Final, Generic, TypeVar
T = TypeVar("T")
class StructureSpec(Generic[T]):
required_attrs: list[tuple[str, Callable]]
optional_attrs: list[tuple[str, Callable]]
cls: type[T]
def __init__(
self,
req_attrs: list[tuple[str, Callable]],
optional_attrs: list[tuple[str, Callable]],
cls: type[T],
) -> None:
self.required_attrs = req_attrs
self.optional_attrs = optional_attrs
self.cls = cls
def structure_attrs_fromdict(val: dict[str, Any], spec: StructureSpec[T]) -> T:
kwargs = {an: ac(val[an]) for an, ac in spec.required_attrs}
for an, ac in spec.optional_attrs:
if an in val:
kwargs[an] = ac(val[an])
return spec.cls(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment