Debian Codegraph @

src/globus_sdk/_internal/guards.py

raw
1 from __future__ import annotations
2
3 import sys
4 import typing as t
5 import uuid
6
7 # some error types use guards, so import from the specific module to avoid circularity
8 from globus_sdk.exc.base import ValidationError
9
10 if t.TYPE_CHECKING:
11 from globus_sdk._internal.serializable import Serializable
12
13 if sys.version_info >= (3, 10):
14 from typing import TypeGuard
15 else:
16 from typing_extensions import TypeGuard
17
18 T = t.TypeVar("T")
19 S = t.TypeVar("S", bound="Serializable")
20
21
22 def is_list_of(data: t.Any, typ: type[T]) -> TypeGuard[list[T]]:
23 return isinstance(data, list) and all(isinstance(item, typ) for item in data)
24
25
26 def is_optional(data: t.Any, typ: type[T]) -> TypeGuard[T | None]:
27 return data is None or isinstance(data, typ)
28
29
30 def is_optional_list_of(data: t.Any, typ: type[T]) -> TypeGuard[list[T] | None]:
31 return data is None or (
32 isinstance(data, list) and all(isinstance(item, typ) for item in data)
33 )
34
35
36 # this class is a namespace, separating validators (which error) from TypeGuards
37 class validators:
38 @staticmethod
39 def str_(name: str, value: t.Any) -> str:
40 if isinstance(value, str):
41 return value
42 raise ValidationError(f"'{name}' must be a string")
43
44 @staticmethod
45 def int_(name: str, value: t.Any) -> int:
46 if isinstance(value, int):
47 return value
48 raise ValidationError(f"'{name}' must be an int")
49
50 @staticmethod
51 def opt_str(name: str, value: t.Any) -> str | None:
52 if is_optional(value, str):
53 return value
54 raise ValidationError(f"'{name}' must be a string or null")
55
56 @staticmethod
57 def opt_bool(name: str, value: t.Any) -> bool | None:
58 if is_optional(value, bool):
59 return value
60 raise ValidationError(f"'{name}' must be a bool or null")
61
62 @staticmethod
63 def str_list(name: str, value: t.Any) -> list[str]:
64 if is_list_of(value, str):
65 return value
66 raise ValidationError(f"'{name}' must be a list of strings")
67
68 @staticmethod
69 def opt_str_list(name: str, value: t.Any) -> list[str] | None:
70 if is_optional_list_of(value, str):
71 return value
72 raise ValidationError(f"'{name}' must be a list of strings or null")
73
74 @staticmethod
75 def opt_str_list_or_commasep(name: str, value: t.Any) -> list[str] | None:
76 if is_optional_list_of(value, str):
77 return value
78 if isinstance(value, str):
79 return value.split(",")
80 raise ValidationError(
81 f"'{name}' must be a list of strings or a comma-delimited string or null"
82 )
83
84 @staticmethod
85 def instance_or_dict(name: str, value: t.Any, cls: type[S]) -> S:
86 if isinstance(value, cls):
87 return value
88 if isinstance(value, dict):
89 return cls.from_dict(value)
90 raise ValidationError(
91 f"'{name}' must be a '{cls.__name__}' object or a dictionary"
92 )
93
94 @staticmethod
95 def uuidlike(name: str, s: t.Any) -> uuid.UUID | str:
96 """
97 Raise an error if the input is not a UUID
98
99 :param s: the UUID|str value
100 :param name: the name for this value to use in error messages
101
102 :raises TypeError: if the input is not a UUID|str
103 :raises ValueError: if the input is a non-UUID str
104
105 Example usage:
106
107 .. code-block:: python
108
109 def frob_it(collection_id: uuid.UUID | str) -> Frob:
110 validators.uuidlike(collection_id, name="collection_id")
111 return Frob(collection_id)
112
113 """
114 if isinstance(s, uuid.UUID):
115 return s
116 elif not isinstance(s, str):
117 raise ValidationError(f"'{name}' must be a UUID or str (value='{s}')")
118
119 try:
120 uuid.UUID(s)
121 except ValueError as e:
122 raise ValidationError(f"'{name}' must be a valid UUID (value='{s}')") from e
123
124 return s