Created
August 6, 2022 17:46
-
-
Save Tinche/ba3ece47874091945a95f15e7fe25096 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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