Skip to content

Commit a432239

Browse files
committed
Refactor string .format() to f-string syntax. Minor corrections. Blackened project.
Rebased to trigger ci. Blackened project, due to Travis failures. f-string formatting where applicable. Minor corrections to language. Corrected typo, missing parens. Update test_structures.py to match updated phrasing. Bowing to the wisdom of black. As per black, adjusted line length in types/argument.py (line 67). One more kick in the pants by black. More f-strings. More blackening.
1 parent 67c4310 commit a432239

29 files changed

+125
-153
lines changed

UPGRADE-v2.0.md

+1-4
Original file line numberDiff line numberDiff line change
@@ -379,10 +379,7 @@ class Base(ObjectType):
379379
id = ID()
380380

381381
def resolve_id(self, info):
382-
return "{type}_{id}".format(
383-
type=self.__class__.__name__,
384-
id=self.id
385-
)
382+
return f"{self.__class__.__name__}_{self.id}"
386383
```
387384

388385
### UUID Scalar

docs/relay/nodes.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ Example of a custom node:
5252
5353
@staticmethod
5454
def to_global_id(type, id):
55-
return '{}:{}'.format(type, id)
55+
return f'{type}:{id}'
5656
5757
@staticmethod
5858
def get_node_from_global_id(info, global_id, only_type=None):

docs/types/objecttypes.rst

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ This example model defines a Person, with a first and a last name:
2626
full_name = graphene.String()
2727
2828
def resolve_full_name(root, info):
29-
return '{} {}'.format(root.first_name, root.last_name)
29+
return f'{root.first_name} {root.last_name}'
3030
3131
**first\_name** and **last\_name** are fields of the ObjectType. Each
3232
field is specified as a class attribute, and each attribute maps to a
@@ -173,7 +173,7 @@ A field can use a custom resolver from outside the class:
173173
import graphene
174174
175175
def resolve_full_name(person, info):
176-
return '{} {}'.format(person.first_name, person.last_name)
176+
return f'{person.first_name} {person.last_name}'
177177
178178
class Person(graphene.ObjectType):
179179
first_name = graphene.String()

examples/complex_example.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ class GeoInput(graphene.InputObjectType):
77

88
@property
99
def latlng(self):
10-
return "({},{})".format(self.lat, self.lng)
10+
return f"({self.lat},{self.lng})"
1111

1212

1313
class Address(graphene.ObjectType):

graphene/pyutils/signature.py

+25-29
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def signature(obj):
5454
"""Get a signature object for the passed callable."""
5555

5656
if not callable(obj):
57-
raise TypeError("{!r} is not a callable object".format(obj))
57+
raise TypeError(f"{repr(obj)} is not a callable object")
5858

5959
if isinstance(obj, types.MethodType):
6060
sig = signature(obj.__func__)
@@ -101,7 +101,7 @@ def signature(obj):
101101
try:
102102
ba = sig.bind_partial(*partial_args, **partial_keywords)
103103
except TypeError as ex:
104-
msg = "partial object {!r} has incorrect arguments".format(obj)
104+
msg = f"partial object {repr(obj)} has incorrect arguments"
105105
raise ValueError(msg)
106106

107107
for arg_name, arg_value in ba.arguments.items():
@@ -171,10 +171,10 @@ def signature(obj):
171171

172172
if isinstance(obj, types.BuiltinFunctionType):
173173
# Raise a nicer error message for builtins
174-
msg = "no signature found for builtin function {!r}".format(obj)
174+
msg = f"no signature found for builtin function {repr(obj)}"
175175
raise ValueError(msg)
176176

177-
raise ValueError("callable {!r} is not supported by signature".format(obj))
177+
raise ValueError(f"callable {repr(obj)} is not supported by signature")
178178

179179

180180
class _void(object):
@@ -195,7 +195,7 @@ def __str__(self):
195195
return self._name
196196

197197
def __repr__(self):
198-
return "<_ParameterKind: {!r}>".format(self._name)
198+
return f"<_ParameterKind: {repr(self._name)}>"
199199

200200

201201
_POSITIONAL_ONLY = _ParameterKind(0, name="POSITIONAL_ONLY")
@@ -249,7 +249,7 @@ def __init__(
249249

250250
if default is not _empty:
251251
if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
252-
msg = "{} parameters cannot have default values".format(kind)
252+
msg = f"{kind} parameters cannot have default values"
253253
raise ValueError(msg)
254254
self._default = default
255255
self._annotation = annotation
@@ -263,7 +263,7 @@ def __init__(
263263
else:
264264
name = str(name)
265265
if kind != _POSITIONAL_ONLY and not re.match(r"[a-z_]\w*$", name, re.I):
266-
msg = "{!r} is not a valid parameter name".format(name)
266+
msg = f"{repr(name)} is not a valid parameter name"
267267
raise ValueError(msg)
268268
self._name = name
269269

@@ -325,14 +325,14 @@ def __str__(self):
325325
if kind == _POSITIONAL_ONLY:
326326
if formatted is None:
327327
formatted = ""
328-
formatted = "<{}>".format(formatted)
328+
formatted = f"<{formatted}>"
329329

330330
# Add annotation and default value
331331
if self._annotation is not _empty:
332-
formatted = "{}:{}".format(formatted, formatannotation(self._annotation))
332+
formatted = f"{formatted}:{formatannotation(self._annotation)}"
333333

334334
if self._default is not _empty:
335-
formatted = "{}={}".format(formatted, repr(self._default))
335+
formatted = f"{formatted}={repr(self._default)}"
336336

337337
if kind == _VAR_POSITIONAL:
338338
formatted = "*" + formatted
@@ -342,10 +342,10 @@ def __str__(self):
342342
return formatted
343343

344344
def __repr__(self):
345-
return "<{} at {:#x} {!r}>".format(self.__class__.__name__, id(self), self.name)
345+
return f"<{self.__class__.__name__} at {id(self):#x} {repr(self.name)}>"
346346

347347
def __hash__(self):
348-
msg = "unhashable type: '{}'".format(self.__class__.__name__)
348+
msg = f"unhashable type: '{self.__class__.__name__}'"
349349
raise TypeError(msg)
350350

351351
def __eq__(self, other):
@@ -442,7 +442,7 @@ def kwargs(self):
442442
return kwargs
443443

444444
def __hash__(self):
445-
msg = "unhashable type: '{}'".format(self.__class__.__name__)
445+
msg = f"unhashable type: '{self.__class__.__name__}'"
446446
raise TypeError(msg)
447447

448448
def __eq__(self, other):
@@ -501,8 +501,7 @@ def __init__(
501501
for idx, param in enumerate(parameters):
502502
kind = param.kind
503503
if kind < top_kind:
504-
msg = "wrong parameter order: {0} before {1}"
505-
msg = msg.format(top_kind, param.kind)
504+
msg = f"wrong parameter order: {top_kind} before {param.kind}"
506505
raise ValueError(msg)
507506
else:
508507
top_kind = kind
@@ -513,7 +512,7 @@ def __init__(
513512
param = param.replace(name=name)
514513

515514
if name in params:
516-
msg = "duplicate parameter name: {!r}".format(name)
515+
msg = f"duplicate parameter name: {repr(name)}"
517516
raise ValueError(msg)
518517
params[name] = param
519518
else:
@@ -527,7 +526,7 @@ def from_function(cls, func):
527526
"""Constructs Signature for the given python function"""
528527

529528
if not isinstance(func, types.FunctionType):
530-
raise TypeError("{!r} is not a Python function".format(func))
529+
raise TypeError(f"{repr(func)} is not a Python function")
531530

532531
Parameter = cls._parameter_cls
533532

@@ -631,7 +630,7 @@ def replace(self, parameters=_void, return_annotation=_void):
631630
return type(self)(parameters, return_annotation=return_annotation)
632631

633632
def __hash__(self):
634-
msg = "unhashable type: '{}'".format(self.__class__.__name__)
633+
msg = f"unhashable type: '{self.__class__.__name__}'"
635634
raise TypeError(msg)
636635

637636
def __eq__(self, other):
@@ -708,10 +707,9 @@ def _bind(self, args, kwargs, partial=False):
708707
elif param.name in kwargs:
709708
if param.kind == _POSITIONAL_ONLY:
710709
msg = (
711-
"{arg!r} parameter is positional only, "
710+
f"{repr(param.name)} parameter is positional only, "
712711
"but was passed as a keyword"
713712
)
714-
msg = msg.format(arg=param.name)
715713
raise TypeError(msg)
716714
parameters_ex = (param,)
717715
break
@@ -726,8 +724,7 @@ def _bind(self, args, kwargs, partial=False):
726724
parameters_ex = (param,)
727725
break
728726
else:
729-
msg = "{arg!r} parameter lacking default value"
730-
msg = msg.format(arg=param.name)
727+
msg = f"{repr(param.name)} parameter lacking default value"
731728
raise TypeError(msg)
732729
else:
733730
# We have a positional argument to process
@@ -752,8 +749,7 @@ def _bind(self, args, kwargs, partial=False):
752749

753750
if param.name in kwargs:
754751
raise TypeError(
755-
"multiple values for argument "
756-
"{arg!r}".format(arg=param.name)
752+
f"multiple values for argument {repr(param.name)}"
757753
)
758754

759755
arguments[param.name] = arg_val
@@ -767,8 +763,8 @@ def _bind(self, args, kwargs, partial=False):
767763
# Signature object (but let's have this check here
768764
# to ensure correct behaviour just in case)
769765
raise TypeError(
770-
"{arg!r} parameter is positional only, "
771-
"but was passed as a keyword".format(arg=param.name)
766+
f"{repr(param.name)} parameter is positional only, "
767+
"but was passed as a keyword"
772768
)
773769

774770
if param.kind == _VAR_KEYWORD:
@@ -790,7 +786,7 @@ def _bind(self, args, kwargs, partial=False):
790786
and param.default is _empty
791787
):
792788
raise TypeError(
793-
"{arg!r} parameter lacking default value".format(arg=param_name)
789+
f"{repr(param_name)} parameter lacking default value"
794790
)
795791

796792
else:
@@ -841,10 +837,10 @@ def __str__(self):
841837

842838
result.append(formatted)
843839

844-
rendered = "({})".format(", ".join(result))
840+
rendered = f"({', '.join(result)})"
845841

846842
if self.return_annotation is not _empty:
847843
anno = formatannotation(self.return_annotation)
848-
rendered += " -> {}".format(anno)
844+
rendered += f" -> {anno}"
849845

850846
return rendered

graphene/relay/connection.py

+11-15
Original file line numberDiff line numberDiff line change
@@ -52,16 +52,14 @@ class Meta:
5252
@classmethod
5353
def __init_subclass_with_meta__(cls, node=None, name=None, **options):
5454
_meta = ConnectionOptions(cls)
55-
assert node, "You have to provide a node in {}.Meta".format(cls.__name__)
55+
assert node, f"You have to provide a node in {cls.__name__}.Meta"
5656
assert isinstance(node, NonNull) or issubclass(
5757
node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)
58-
), ('Received incompatible node "{}" for Connection {}.').format(
59-
node, cls.__name__
60-
)
58+
), f'Received incompatible node "{node}" for Connection {cls.__name__}.'
6159

6260
base_name = re.sub("Connection$", "", name or cls.__name__) or node._meta.name
6361
if not name:
64-
name = "{}Connection".format(base_name)
62+
name = f"{base_name}Connection"
6563

6664
edge_class = getattr(cls, "Edge", None)
6765
_node = node
@@ -71,11 +69,9 @@ class EdgeBase(object):
7169
cursor = String(required=True, description="A cursor for use in pagination")
7270

7371
class EdgeMeta:
74-
description = "A Relay edge containing a `{}` and its cursor.".format(
75-
base_name
76-
)
72+
description = f"A Relay edge containing a `{base_name}` and its cursor."
7773

78-
edge_name = "{}Edge".format(base_name)
74+
edge_name = f"{base_name}Edge"
7975
if edge_class:
8076
edge_bases = (edge_class, EdgeBase, ObjectType)
8177
else:
@@ -132,9 +128,9 @@ def type(self):
132128
"Read more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#node-connections"
133129
)
134130

135-
assert issubclass(connection_type, Connection), (
136-
'{} type have to be a subclass of Connection. Received "{}".'
137-
).format(self.__class__.__name__, connection_type)
131+
assert issubclass(
132+
connection_type, Connection
133+
), f'{self.__class__.__name__} type have to be a subclass of Connection. Received "{connection_type}".'
138134
return type
139135

140136
@classmethod
@@ -143,9 +139,9 @@ def resolve_connection(cls, connection_type, args, resolved):
143139
return resolved
144140

145141
assert isinstance(resolved, Iterable), (
146-
"Resolved value from the connection field have to be iterable or instance of {}. "
147-
'Received "{}"'
148-
).format(connection_type, resolved)
142+
f"Resolved value from the connection field has to be iterable or instance of {connection_type}. "
143+
f'Received "{resolved}"'
144+
)
149145
connection = connection_from_list(
150146
resolved,
151147
args,

graphene/relay/mutation.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def __init_subclass_with_meta__(
2828
input_fields = {}
2929

3030
cls.Input = type(
31-
"{}Input".format(base_name),
31+
f"{base_name}Input",
3232
bases,
3333
OrderedDict(
3434
input_fields, client_mutation_id=String(name="clientMutationId")
@@ -42,12 +42,12 @@ def __init_subclass_with_meta__(
4242
mutate_and_get_payload = getattr(cls, "mutate_and_get_payload", None)
4343
if cls.mutate and cls.mutate.__func__ == ClientIDMutation.mutate.__func__:
4444
assert mutate_and_get_payload, (
45-
"{name}.mutate_and_get_payload method is required"
45+
f"{name or cls.__name__}.mutate_and_get_payload method is required"
4646
" in a ClientIDMutation."
47-
).format(name=name or cls.__name__)
47+
)
4848

4949
if not name:
50-
name = "{}Payload".format(base_name)
50+
name = f"{base_name}Payload"
5151

5252
super(ClientIDMutation, cls).__init_subclass_with_meta__(
5353
output=None, arguments=arguments, name=name, **options
@@ -61,8 +61,8 @@ def on_resolve(payload):
6161
payload.client_mutation_id = input.get("client_mutation_id")
6262
except Exception:
6363
raise Exception(
64-
("Cannot set client_mutation_id in the payload object {}").format(
65-
repr(payload)
64+
(
65+
f"Cannot set client_mutation_id in the payload object {repr(payload)}"
6666
)
6767
)
6868
return payload

graphene/relay/node.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,9 @@ def get_node_from_global_id(cls, info, global_id, only_type=None):
9898
return None
9999

100100
if only_type:
101-
assert graphene_type == only_type, ("Must receive a {} id.").format(
102-
only_type._meta.name
103-
)
101+
assert (
102+
graphene_type == only_type
103+
), f"Must receive a {only_type._meta.name} id."
104104

105105
# We make sure the ObjectType implements the "Node" interface
106106
if cls not in graphene_type._meta.interfaces:

graphene/types/argument.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -64,18 +64,17 @@ def to_arguments(args, extra_args=None):
6464

6565
if isinstance(arg, (InputField, Field)):
6666
raise ValueError(
67-
"Expected {} to be Argument, but received {}. Try using Argument({}).".format(
68-
default_name, type(arg).__name__, arg.type
69-
)
67+
f"Expected {default_name} to be Argument, but received {type(arg).__name__}. "
68+
f"Try using Argument({arg.type})."
7069
)
7170

7271
if not isinstance(arg, Argument):
73-
raise ValueError('Unknown argument "{}".'.format(default_name))
72+
raise ValueError(f'Unknown argument "{default_name}".')
7473

7574
arg_name = default_name or arg.name
7675
assert (
7776
arg_name not in arguments
78-
), 'More than one Argument have same name "{}".'.format(arg_name)
77+
), f'More than one Argument have same name "{arg_name}".'
7978
arguments[arg_name] = arg
8079

8180
return arguments

graphene/types/base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ def __setattr__(self, name, value):
2020
if not self._frozen:
2121
super(BaseOptions, self).__setattr__(name, value)
2222
else:
23-
raise Exception("Can't modify frozen Options {}".format(self))
23+
raise Exception(f"Can't modify frozen Options {self}")
2424

2525
def __repr__(self):
26-
return "<{} name={}>".format(self.__class__.__name__, repr(self.name))
26+
return f"<{self.__class__.__name__} name={repr(self.name)}>"
2727

2828

2929
class BaseType(SubclassWithMeta):

0 commit comments

Comments
 (0)