forked from CMSgov/beneficiary-fhir-data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpydantic_utils.py
More file actions
38 lines (23 loc) · 994 Bytes
/
Copy pathpydantic_utils.py
File metadata and controls
38 lines (23 loc) · 994 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from dataclasses import dataclass
from functools import lru_cache
from typing import TYPE_CHECKING, Any, TypeVar, cast
from pydantic.main import BaseModel
@dataclass(frozen=True)
class _GetFields:
_model: type[BaseModel]
def __getattr__(self, item: str) -> Any: # noqa: ANN401
if item in self._model.model_fields:
return item
return getattr(self._model, item)
@dataclass(frozen=True)
class _GetAliases:
_model: type[BaseModel]
def __getattr__(self, item: str) -> Any: # noqa: ANN401
if item in self._model.model_fields:
return self._model.model_fields[item].alias or item
return getattr(self._model, item)
TModel = TypeVar("TModel", bound=type[BaseModel])
def fields[TModel: type[BaseModel]](model: TModel, by_alias: bool = False) -> TModel:
return cast(TModel, _GetFields(model)) if not by_alias else cast(TModel, _GetAliases(model))
if not TYPE_CHECKING:
fields = lru_cache(maxsize=256)(fields)