Skip to content

Commit 924bea1

Browse files
committed
Support custom inspect through magic method __inspect__()
Replicates graphql/graphql-js@d7c85a4
1 parent 17e1857 commit 924bea1

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

graphql/pyutils/inspect.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def inspect(value: Any) -> str:
1919
2020
Used to print values in error messages. We do not use repr() in order to not
2121
leak too much of the inner Python representation of unknown objects, and we
22-
do not use json.dumps() because no all objects can be serialized as JSON and
22+
do not use json.dumps() because not all objects can be serialized as JSON and
2323
we want to output strings with single quotes like Python repr() does it.
2424
"""
2525
if isinstance(value, (bool, int, float, str)) or value in (None, INVALID):
@@ -71,6 +71,15 @@ def inspect(value: Any) -> str:
7171
value, (GraphQLNamedType, GraphQLScalarType, GraphQLWrappingType)
7272
):
7373
return str(value)
74+
# check if we have a custom inspect method
75+
try:
76+
inspect_method = value.__inspect__
77+
if not callable(inspect_method):
78+
raise AttributeError
79+
except AttributeError:
80+
pass
81+
else:
82+
return inspect_method()
7483
try:
7584
name = type(value).__name__
7685
if not name or "<" in name or ">" in name:

tests/pyutils/test_inspect.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,3 +159,11 @@ def graphql_types():
159159
"TestObjectType", {"test": GraphQLField(GraphQLString)}
160160
)
161161
assert inspect(test_object_type) == "TestObjectType"
162+
163+
def custom_inspect():
164+
class TestClass:
165+
@staticmethod
166+
def __inspect__():
167+
return "<custom magic method inspect>"
168+
169+
assert inspect(TestClass()) == "<custom magic method inspect>"

0 commit comments

Comments
 (0)