Debian Codegraph @

src/globus_sdk/_internal/serializable.py

raw
1 from __future__ import annotations
2
3 import inspect
4 import sys
5 import typing as t
6
7 if sys.version_info >= (3, 11):
8 from typing import Self
9 else:
10 from typing_extensions import Self
11
12
13 class Serializable:
14 """
15 This is a base class for helpers which represent data which can be
16 loaded to or from a dictionary.
17
18 Serializable classes:
19 - know what fields they have, based on their initializer signatures
20 - support `to_dict()` and `from_dict()` conversions
21 - typically use `globus_sdk._internal.guards.validators` to check attribute types
22 """
23
24 _EXCLUDE_VARS: t.ClassVar[tuple[str, ...]] = ("self", "extra")
25 extra: dict[str, t.Any]
26
27 @classmethod
28 def _supported_fields(cls) -> list[str]:
29 signature = inspect.signature(cls.__init__)
30 return [
31 name
32 for name in signature.parameters.keys()
33 if name not in cls._EXCLUDE_VARS
34 ]
35
36 @classmethod
37 def from_dict(cls, data: dict[str, t.Any]) -> Self:
38 """
39 Instantiate from a dictionary.
40
41 :param data: The dictionary to create the error from.
42 """
43
44 # Extract any extra fields
45 extras = {k: v for k, v in data.items() if k not in cls._supported_fields()}
46 kwargs: dict[str, t.Any] = {"extra": extras}
47 # Ensure required fields are supplied
48 for field_name in cls._supported_fields():
49 kwargs[field_name] = data.get(field_name)
50
51 return cls(**kwargs)
52
53 def to_dict(self, include_extra: bool = False) -> dict[str, t.Any]:
54 """
55 Render to a dictionary.
56
57 :param include_extra: Whether to include stored extra (non-standard) fields in
58 the returned dictionary.
59 """
60 result = {}
61
62 # Set any authorization parameters
63 for field in self._supported_fields():
64 value = getattr(self, field)
65 if value is not None:
66 if isinstance(value, Serializable):
67 value = value.to_dict(include_extra=include_extra)
68 result[field] = value
69
70 # Set any extra fields
71 if include_extra:
72 result.update(self.extra)
73
74 return result