Skip to content

Commit e1a211d

Browse files
committed
GraphQLScalarType: make 'serialize' optional with 'identity_func' as default
It's a logical step since this is what 'build_schema', 'extend_schema' and 'build_client_schema' are doing anyway. Replicates graphql/graphql-js@71d96d7
1 parent 7ee7a2b commit e1a211d

File tree

10 files changed

+24
-48
lines changed

10 files changed

+24
-48
lines changed

graphql/type/definition.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -307,18 +307,18 @@ def serialize_odd(value):
307307
# Serializes an internal value to include in a response.
308308
serialize: GraphQLScalarSerializer
309309
# Parses an externally provided value to use as an input.
310-
parseValue: GraphQLScalarValueParser
310+
parse_value: GraphQLScalarValueParser
311311
# Parses an externally provided literal value to use as an input.
312312
# Takes a dictionary of variables as an optional second argument.
313-
parseLiteral: GraphQLScalarLiteralParser
313+
parse_literal: GraphQLScalarLiteralParser
314314

315315
ast_node: Optional[ScalarTypeDefinitionNode]
316316
extension_ast_nodes: Optional[Tuple[ScalarTypeExtensionNode]]
317317

318318
def __init__(
319319
self,
320320
name: str,
321-
serialize: GraphQLScalarSerializer,
321+
serialize: GraphQLScalarSerializer = None,
322322
description: str = None,
323323
parse_value: GraphQLScalarValueParser = None,
324324
parse_literal: GraphQLScalarLiteralParser = None,
@@ -331,7 +331,7 @@ def __init__(
331331
ast_node=ast_node,
332332
extension_ast_nodes=extension_ast_nodes,
333333
)
334-
if not callable(serialize):
334+
if serialize is not None and not callable(serialize):
335335
raise TypeError(
336336
f"{name} must provide 'serialize' function."
337337
" If this custom Scalar is also used as an input type,"
@@ -352,9 +352,9 @@ def __init__(
352352
raise TypeError(
353353
f"{name} extension AST nodes must be ScalarTypeExtensionNode."
354354
)
355-
self.serialize = serialize # type: ignore
356-
self.parse_value = parse_value or identity_func
357-
self.parse_literal = parse_literal or value_from_ast_untyped
355+
self.serialize = serialize or identity_func # type: ignore
356+
self.parse_value = parse_value or identity_func # type: ignore
357+
self.parse_literal = parse_literal or value_from_ast_untyped # type: ignore
358358

359359
def __repr__(self):
360360
return f"<{self.__class__.__name__} {self.name!r}>"

graphql/utilities/build_ast_schema.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
parse,
2525
Node,
2626
)
27-
from ..pyutils import identity_func, inspect
27+
from ..pyutils import inspect
2828
from ..type import (
2929
GraphQLArgument,
3030
GraphQLDeprecatedDirective,
@@ -385,7 +385,6 @@ def _make_scalar_def(ast_node: ScalarTypeDefinitionNode) -> GraphQLScalarType:
385385
name=ast_node.name.value,
386386
description=ast_node.description.value if ast_node.description else None,
387387
ast_node=ast_node,
388-
serialize=identity_func,
389388
)
390389

391390
def _make_input_object_def(

graphql/utilities/build_client_schema.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from ..error import INVALID
55
from ..language import DirectiveLocation, parse_value
6-
from ..pyutils import identity_func, inspect
6+
from ..pyutils import inspect
77
from ..type import (
88
GraphQLArgument,
99
GraphQLDirective,
@@ -126,7 +126,6 @@ def build_scalar_def(scalar_introspection: Dict) -> GraphQLScalarType:
126126
return GraphQLScalarType(
127127
name=scalar_introspection["name"],
128128
description=scalar_introspection.get("description"),
129-
serialize=identity_func,
130129
)
131130

132131
def build_object_def(object_introspection: Dict) -> GraphQLObjectType:

tests/type/test_definition.py

Lines changed: 8 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
)
2323
from graphql.utilities import value_from_ast_untyped
2424

25-
ScalarType = GraphQLScalarType("Scalar", serialize=lambda: None)
25+
ScalarType = GraphQLScalarType("Scalar")
2626
ObjectType = GraphQLObjectType("Object", {})
2727
InterfaceType = GraphQLInterfaceType("Interface")
2828
UnionType = GraphQLUnionType("Union", [ObjectType], resolve_type=lambda: None)
@@ -37,39 +37,20 @@
3737

3838
def describe_type_system_scalars():
3939
def accepts_a_scalar_type_defining_serialize():
40-
assert GraphQLScalarType("SomeScalar", lambda: None)
40+
assert GraphQLScalarType("SomeScalar")
4141

4242
def accepts_a_scalar_type_defining_parse_value_and_parse_literal():
4343
assert GraphQLScalarType(
44-
"SomeScalar",
45-
serialize=lambda: None,
46-
parse_value=lambda: None,
47-
parse_literal=lambda: None,
44+
"SomeScalar", parse_value=lambda: None, parse_literal=lambda: None
4845
)
4946

5047
def provides_default_methods_if_omitted():
51-
scalar = GraphQLScalarType("Foo", lambda: None)
48+
scalar = GraphQLScalarType("Foo")
5249

50+
assert scalar.serialize is identity_func
5351
assert scalar.parse_value is identity_func
5452
assert scalar.parse_literal is value_from_ast_untyped
5553

56-
def rejects_a_scalar_type_not_defining_serialize():
57-
with raises(
58-
TypeError, match="missing 1 required positional argument: 'serialize'"
59-
):
60-
# noinspection PyArgumentList
61-
GraphQLScalarType("SomeScalar")
62-
with raises(TypeError) as exc_info:
63-
# noinspection PyTypeChecker
64-
GraphQLScalarType("SomeScalar", None)
65-
msg = str(exc_info.value)
66-
assert msg == (
67-
"SomeScalar must provide 'serialize' function."
68-
" If this custom Scalar is also used as an input type,"
69-
" ensure 'parse_value' and 'parse_literal' functions"
70-
" are also provided."
71-
)
72-
7354
def rejects_a_scalar_type_defining_serialize_with_incorrect_type():
7455
with raises(TypeError) as exc_info:
7556
# noinspection PyTypeChecker
@@ -84,7 +65,7 @@ def rejects_a_scalar_type_defining_serialize_with_incorrect_type():
8465

8566
def rejects_a_scalar_type_defining_parse_value_but_not_parse_literal():
8667
with raises(TypeError) as exc_info:
87-
GraphQLScalarType("SomeScalar", lambda: None, parse_value=lambda: None)
68+
GraphQLScalarType("SomeScalar", parse_value=lambda: None)
8869
msg = str(exc_info.value)
8970
assert msg == (
9071
"SomeScalar must provide both"
@@ -93,7 +74,7 @@ def rejects_a_scalar_type_defining_parse_value_but_not_parse_literal():
9374

9475
def rejects_a_scalar_type_defining_parse_literal_but_not_parse_value():
9576
with raises(TypeError) as exc_info:
96-
GraphQLScalarType("SomeScalar", lambda: None, parse_literal=lambda: None)
77+
GraphQLScalarType("SomeScalar", parse_literal=lambda: None)
9778
msg = str(exc_info.value)
9879
assert msg == (
9980
"SomeScalar must provide both"
@@ -103,9 +84,7 @@ def rejects_a_scalar_type_defining_parse_literal_but_not_parse_value():
10384
def rejects_a_scalar_type_incorrectly_defining_parse_literal_and_value():
10485
with raises(TypeError) as exc_info:
10586
# noinspection PyTypeChecker
106-
GraphQLScalarType(
107-
"SomeScalar", lambda: None, parse_value={}, parse_literal={}
108-
)
87+
GraphQLScalarType("SomeScalar", parse_value={}, parse_literal={})
10988
msg = str(exc_info.value)
11089
assert msg == (
11190
"SomeScalar must provide both"

tests/type/test_predicate.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@
7171
UnionType = GraphQLUnionType("Union", types=[ObjectType])
7272
EnumType = GraphQLEnumType("Enum", values={"foo": {}})
7373
InputObjectType = GraphQLInputObjectType("InputObject", {})
74-
ScalarType = GraphQLScalarType("Scalar", lambda: None)
74+
ScalarType = GraphQLScalarType("Scalar")
7575
Directive = GraphQLDirective("Directive", [DirectiveLocation.QUERY])
7676

7777

@@ -573,7 +573,7 @@ def returns_false_for_spec_defined_scalar_type():
573573
assert is_specified_directive(GraphQLString) is False
574574

575575
def returns_false_for_scalar_type_named_like_specified_directive():
576-
ScalarNamedLikeDirective = GraphQLScalarType("deprecated", lambda: None)
576+
ScalarNamedLikeDirective = GraphQLScalarType("deprecated")
577577
assert is_specified_directive(ScalarNamedLikeDirective) is False
578578

579579
def returns_false_for_random_garbage():

tests/type/test_schema.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ def checks_the_configuration_for_mistakes():
209209

210210
def describe_a_schema_must_contain_uniquely_named_types():
211211
def rejects_a_schema_which_redefines_a_built_in_type():
212-
FakeString = GraphQLScalarType("String", serialize=lambda: None)
212+
FakeString = GraphQLScalarType("String")
213213

214214
QueryType = GraphQLObjectType(
215215
"Query",

tests/type/test_validation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
from graphql.utilities import build_schema, extend_schema
3030

3131

32-
SomeScalarType = GraphQLScalarType(name="SomeScalar", serialize=lambda: None)
32+
SomeScalarType = GraphQLScalarType(name="SomeScalar")
3333

3434
SomeInterfaceType = GraphQLInterfaceType(
3535
name="SomeInterface", fields=lambda: {"f": GraphQLField(SomeObjectType)}

tests/utilities/test_extend_schema.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040

4141
# Test schema.
4242

43-
SomeScalarType = GraphQLScalarType(name="SomeScalar", serialize=lambda x: x)
43+
SomeScalarType = GraphQLScalarType(name="SomeScalar")
4444

4545
SomeInterfaceType = GraphQLInterfaceType(
4646
name="SomeInterface",

tests/utilities/test_schema_printer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,7 @@ def prints_input_type():
410410
)
411411

412412
def prints_custom_scalar():
413-
odd_type = GraphQLScalarType(name="Odd", serialize=lambda: None)
413+
odd_type = GraphQLScalarType(name="Odd")
414414

415415
schema = GraphQLSchema(types=[odd_type])
416416
output = print_for_test(schema)

tests/validation/harness.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,6 @@ def raise_type_error(message):
230230

231231
InvalidScalar = GraphQLScalarType(
232232
name="Invalid",
233-
serialize=lambda value: value,
234233
parse_literal=lambda value_node: raise_type_error(
235234
f"Invalid scalar is always invalid: {print_ast(value_node)}"
236235
),
@@ -239,7 +238,7 @@ def raise_type_error(message):
239238
),
240239
)
241240

242-
AnyScalar = GraphQLScalarType(name="Any", serialize=lambda value: value)
241+
AnyScalar = GraphQLScalarType(name="Any")
243242

244243
QueryRoot = GraphQLObjectType(
245244
"QueryRoot",

0 commit comments

Comments
 (0)