Debian Codegraph @

src/graphql/pyutils/inspect.py

raw
1 from inspect import (
2 isclass,
3 ismethod,
4 isfunction,
5 isgeneratorfunction,
6 isgenerator,
7 iscoroutinefunction,
8 iscoroutine,
9 isasyncgenfunction,
10 isasyncgen,
11 )
12 from typing import Any, List
13
14 from .undefined import Undefined
15
16 __all__ = ["inspect"]
17
18 max_recursive_depth = 2
19 max_str_size = 240
20 max_list_size = 10
21
22
23 def inspect(value: Any) -> str:
24 """Inspect value and a return string representation for error messages.
25
26 Used to print values in error messages. We do not use repr() in order to not
27 leak too much of the inner Python representation of unknown objects, and we
28 do not use json.dumps() because not all objects can be serialized as JSON and
29 we want to output strings with single quotes like Python repr() does it.
30
31 We also restrict the size of the representation by truncating strings and
32 collections and allowing only a maximum recursion depth.
33 """
34 return inspect_recursive(value, [])
35
36
37 def inspect_recursive(value: Any, seen_values: List) -> str:
38 if value is None or value is Undefined or isinstance(value, (bool, float, complex)):
39 return repr(value)
40 if isinstance(value, (int, str, bytes, bytearray)):
41 return trunc_str(repr(value))
42 if len(seen_values) < max_recursive_depth and value not in seen_values:
43 # check if we have a custom inspect method
44 inspect_method = getattr(value, "__inspect__", None)
45 if inspect_method is not None and callable(inspect_method):
46 s = inspect_method()
47 if isinstance(s, str):
48 return trunc_str(s)
49 seen_values = [*seen_values, value]
50 return inspect_recursive(s, seen_values)
51 # recursively inspect collections
52 if isinstance(value, (list, tuple, dict, set, frozenset)):
53 if not value:
54 return repr(value)
55 seen_values = [*seen_values, value]
56 if isinstance(value, list):
57 items = value
58 elif isinstance(value, dict):
59 items = list(value.items())
60 else:
61 items = list(value)
62 items = trunc_list(items)
63 if isinstance(value, dict):
64 s = ", ".join(
65 (
66 "..."
67 if v is ELLIPSIS
68 else inspect_recursive(v[0], seen_values)
69 + ": "
70 + inspect_recursive(v[1], seen_values)
71 )
72 for v in items
73 )
74 else:
75 s = ", ".join(
76 "..." if v is ELLIPSIS else inspect_recursive(v, seen_values)
77 for v in items
78 )
79 if isinstance(value, tuple):
80 if len(items) == 1:
81 return f"({s},)"
82 return f"({s})"
83 if isinstance(value, (dict, set)):
84 return "{" + s + "}"
85 if isinstance(value, frozenset):
86 return f"frozenset({{{s}}})"
87 return f"[{s}]"
88 else:
89 # handle collections that are nested too deep
90 if isinstance(value, (list, tuple, dict, set, frozenset)):
91 if not value:
92 return repr(value)
93 if isinstance(value, list):
94 return "[...]"
95 if isinstance(value, tuple):
96 return "(...)"
97 if isinstance(value, dict):
98 return "{...}"
99 if isinstance(value, set):
100 return "set(...)"
101 return "frozenset(...)"
102 if isinstance(value, Exception):
103 type_ = "exception"
104 value = type(value)
105 elif isclass(value):
106 type_ = "exception class" if issubclass(value, Exception) else "class"
107 elif ismethod(value):
108 type_ = "method"
109 elif iscoroutinefunction(value):
110 type_ = "coroutine function"
111 elif isasyncgenfunction(value):
112 type_ = "async generator function"
113 elif isgeneratorfunction(value):
114 type_ = "generator function"
115 elif isfunction(value):
116 type_ = "function"
117 elif iscoroutine(value):
118 type_ = "coroutine"
119 elif isasyncgen(value):
120 type_ = "async generator"
121 elif isgenerator(value):
122 type_ = "generator"
123 else:
124 # stringify (only) the well-known GraphQL types
125 from ..type import (
126 GraphQLDirective,
127 GraphQLNamedType,
128 GraphQLScalarType,
129 GraphQLWrappingType,
130 )
131
132 if isinstance(
133 value,
134 (
135 GraphQLDirective,
136 GraphQLNamedType,
137 GraphQLScalarType,
138 GraphQLWrappingType,
139 ),
140 ):
141 return str(value)
142 try:
143 name = type(value).__name__
144 if not name or "<" in name or ">" in name:
145 raise AttributeError
146 except AttributeError:
147 return "<object>"
148 else:
149 return f"<{name} instance>"
150 try:
151 name = value.__name__
152 if not name or "<" in name or ">" in name:
153 raise AttributeError
154 except AttributeError:
155 return f"<{type_}>"
156 else:
157 return f"<{type_} {name}>"
158
159
160 def trunc_str(s: str) -> str:
161 """Truncate strings to maximum length."""
162 if len(s) > max_str_size:
163 i = max(0, (max_str_size - 3) // 2)
164 j = max(0, max_str_size - 3 - i)
165 s = s[:i] + "..." + s[-j:]
166 return s
167
168
169 def trunc_list(s: List) -> List:
170 """Truncate lists to maximum length."""
171 if len(s) > max_list_size:
172 i = max_list_size // 2
173 j = i - 1
174 s = s[:i] + [ELLIPSIS] + s[-j:]
175 return s
176
177
178 class InspectEllipsisType:
179 """Singleton class for indicating ellipses in iterables."""
180
181
182 ELLIPSIS = InspectEllipsisType()