Debian Codegraph @

src/globus_sdk/_missing.py

raw
1 """
2 The definition of the MISSING sentinel and its type.
3
4 These are exposed publicly as `globus_sdk.MISSING` and `globus_sdk.MissingType`.
5 """
6
7 from __future__ import annotations
8
9 import typing as t
10
11 T = t.TypeVar("T")
12
13 # type checkers don't know that MISSING is a sentinel, so we will describe it
14 # differently at typing time, allowing for type narrowing on `is MISSING` and
15 # similar checks
16 if t.TYPE_CHECKING:
17 # pretend that `MISSING: MissingType` is an enum at type-checking time
18 #
19 # enums are treated as `Literal[...]` values and are narrowed under simple
20 # checks, as unions and literal types are
21 # therefore, under this definition, `MissingType ~= Literal[MissingType.MISSING]`
22 #
23 # Therefore, consider this example:
24 #
25 # x: int | float | MissingType
26 # if x is not MISSING:
27 # reveal_type(x)
28 #
29 # This is effectively the same as if we wrote:
30 #
31 # x: int | float | Literal["a"]
32 # if x != "a":
33 # reveal_type(x)
34 #
35 # Both should show `x: int | float`
36 import enum
37
38 class MissingType(enum.Enum):
39 MISSING = enum.auto()
40
41 MISSING = MissingType.MISSING
42 else:
43
44 class MissingType:
45 def __init__(self) -> None:
46 # disable instantiation, but gated to be able to run once
47 # when this module is imported
48 if "MISSING" in globals():
49 raise TypeError("MissingType should not be instantiated")
50
51 def __bool__(self) -> bool:
52 return False
53
54 def __copy__(self) -> MissingType:
55 return self
56
57 def __deepcopy__(self, memo: dict[int, t.Any]) -> MissingType:
58 return self
59
60 # unpickling a MissingType should always return the "MISSING" sentinel
61 def __reduce__(self) -> str:
62 return "MISSING"
63
64 def __repr__(self) -> str:
65 return "<globus_sdk.MISSING>"
66
67 # a sentinel value for "missing" values which are distinguished from `None` (null)
68 # this is the default used to indicate that a parameter was not passed, so that
69 # method calls passing `None` can be distinguished from those which did not pass any
70 # value
71 # users should typically not use this value directly, but it is part of the
72 # public SDK interfaces along with its type for annotation purposes
73 MISSING = MissingType()
74
75
76 @t.overload
77 def filter_missing(data: dict[str, t.Any]) -> dict[str, t.Any]: ...
78
79
80 @t.overload
81 def filter_missing(data: None) -> None: ...
82
83
84 def filter_missing(data: dict[str, t.Any] | None) -> dict[str, t.Any] | None:
85 if data is None:
86 return None
87 return {k: v for k, v in data.items() if v is not MISSING}
88
89
90 def none2missing(obj: T | None) -> T | MissingType:
91 """
92 A converter for interfaces which take "nullable" to mean "omittable", to
93 adapt them to usage sites which require use of MISSING for omittable
94 elements.
95
96 :param obj: The nullable object to convert to an omittable object.
97 """
98 if obj is None:
99 return MISSING
100 return obj