Skip to content

Commit 60a9609

Browse files
authored
Updated all str.format(…) to f-strings (#1158)
* Updated all str.format(…) to f-strings This revamps the PR #984 * Pass black * Fix flake8 * Updated objecttype * Fix black version
1 parent 1418301 commit 60a9609

30 files changed

+136
-183
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ repos:
1818
hooks:
1919
- id: pyupgrade
2020
- repo: https://github.com/ambv/black
21-
rev: 19.3b0
21+
rev: 19.10b0
2222
hooks:
2323
- id: black
2424
language_version: python3

UPGRADE-v2.0.md

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -377,10 +377,7 @@ class Base(ObjectType):
377377
id = ID()
378378

379379
def resolve_id(root, info):
380-
return "{type}_{id}".format(
381-
type=root.__class__.__name__,
382-
id=root.id
383-
)
380+
return f"{root.__class__.__name__}_{root.id}"
384381
```
385382

386383
### UUID Scalar

docs/execution/middleware.rst

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,9 @@ logs the time it takes to resolve each field
5555
def timing_middleware(next, root, info, **args):
5656
start = timer()
5757
return_value = next(root, info, **args)
58-
duration = timer() - start
59-
logger.debug("{parent_type}.{field_name}: {duration} ms".format(
60-
parent_type=root._meta.name if root and hasattr(root, '_meta') else '',
61-
field_name=info.field_name,
62-
duration=round(duration * 1000, 2)
63-
))
58+
duration = round((timer() - start) * 1000, 2)
59+
parent_type_name = root._meta.name if root and hasattr(root, '_meta') else ''
60+
logger.debug(f"{parent_type_name}.{info.field_name}: {duration} ms")
6461
return return_value
6562
6663

docs/relay/nodes.rst

Lines changed: 1 addition & 1 deletion
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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ A field can use a custom resolver from outside the class:
331331
from graphene import ObjectType, String
332332
333333
def resolve_full_name(person, info):
334-
return '{} {}'.format(person.first_name, person.last_name)
334+
return f"{person.first_name} {person.last_name}"
335335
336336
class Person(ObjectType):
337337
first_name = String()

examples/complex_example.py

Lines changed: 1 addition & 1 deletion
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/relay/connection.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,14 @@ class Meta:
6363
@classmethod
6464
def __init_subclass_with_meta__(cls, node=None, name=None, **options):
6565
_meta = ConnectionOptions(cls)
66-
assert node, "You have to provide a node in {}.Meta".format(cls.__name__)
66+
assert node, f"You have to provide a node in {cls.__name__}.Meta"
6767
assert isinstance(node, NonNull) or issubclass(
6868
node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)
69-
), ('Received incompatible node "{}" for Connection {}.').format(
70-
node, cls.__name__
71-
)
69+
), f'Received incompatible node "{node}" for Connection {cls.__name__}.'
7270

7371
base_name = re.sub("Connection$", "", name or cls.__name__) or node._meta.name
7472
if not name:
75-
name = "{}Connection".format(base_name)
73+
name = f"{base_name}Connection"
7674

7775
edge_class = getattr(cls, "Edge", None)
7876
_node = node
@@ -82,11 +80,9 @@ class EdgeBase:
8280
cursor = String(required=True, description="A cursor for use in pagination")
8381

8482
class EdgeMeta:
85-
description = "A Relay edge containing a `{}` and its cursor.".format(
86-
base_name
87-
)
83+
description = f"A Relay edge containing a `{base_name}` and its cursor."
8884

89-
edge_name = "{}Edge".format(base_name)
85+
edge_name = f"{base_name}Edge"
9086
if edge_class:
9187
edge_bases = (edge_class, EdgeBase, ObjectType)
9288
else:
@@ -141,9 +137,9 @@ def type(self):
141137
"Read more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#node-connections"
142138
)
143139

144-
assert issubclass(connection_type, Connection), (
145-
'{} type has to be a subclass of Connection. Received "{}".'
146-
).format(self.__class__.__name__, connection_type)
140+
assert issubclass(
141+
connection_type, Connection
142+
), f'{self.__class__.__name__} type has to be a subclass of Connection. Received "{connection_type}".'
147143
return type
148144

149145
@classmethod
@@ -152,9 +148,9 @@ def resolve_connection(cls, connection_type, args, resolved):
152148
return resolved
153149

154150
assert isinstance(resolved, Iterable), (
155-
"Resolved value from the connection field has to be an iterable or instance of {}. "
156-
'Received "{}"'
157-
).format(connection_type, resolved)
151+
f"Resolved value from the connection field has to be an iterable or instance of {connection_type}. "
152+
f'Received "{resolved}"'
153+
)
158154
connection = connection_from_array(
159155
resolved,
160156
args,

graphene/relay/mutation.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def __init_subclass_with_meta__(
2727
input_fields = {}
2828

2929
cls.Input = type(
30-
"{}Input".format(base_name),
30+
f"{base_name}Input",
3131
bases,
3232
dict(input_fields, client_mutation_id=String(name="clientMutationId")),
3333
)
@@ -39,12 +39,12 @@ def __init_subclass_with_meta__(
3939
mutate_and_get_payload = getattr(cls, "mutate_and_get_payload", None)
4040
if cls.mutate and cls.mutate.__func__ == ClientIDMutation.mutate.__func__:
4141
assert mutate_and_get_payload, (
42-
"{name}.mutate_and_get_payload method is required"
42+
f"{name or cls.__name__}.mutate_and_get_payload method is required"
4343
" in a ClientIDMutation."
44-
).format(name=name or cls.__name__)
44+
)
4545

4646
if not name:
47-
name = "{}Payload".format(base_name)
47+
name = f"{base_name}Payload"
4848

4949
super(ClientIDMutation, cls).__init_subclass_with_meta__(
5050
output=None, arguments=arguments, name=name, **options
@@ -58,9 +58,7 @@ def on_resolve(payload):
5858
payload.client_mutation_id = input.get("client_mutation_id")
5959
except Exception:
6060
raise Exception(
61-
("Cannot set client_mutation_id in the payload object {}").format(
62-
repr(payload)
63-
)
61+
f"Cannot set client_mutation_id in the payload object {repr(payload)}"
6462
)
6563
return payload
6664

graphene/relay/node.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def __init__(self, node, type=False, **kwargs):
5757
# interface
5858
type or node,
5959
id=ID(required=True, description="The ID of the object"),
60-
**kwargs
60+
**kwargs,
6161
)
6262

6363
def get_resolver(self, parent_resolver):
@@ -93,33 +93,27 @@ def get_node_from_global_id(cls, info, global_id, only_type=None):
9393
except Exception as e:
9494
raise Exception(
9595
(
96-
'Unable to parse global ID "{global_id}". '
96+
f'Unable to parse global ID "{global_id}". '
9797
'Make sure it is a base64 encoded string in the format: "TypeName:id". '
98-
"Exception message: {exception}".format(
99-
global_id=global_id, exception=str(e)
100-
)
98+
f"Exception message: {str(e)}"
10199
)
102100
)
103101

104102
graphene_type = info.schema.get_type(_type)
105103
if graphene_type is None:
106-
raise Exception(
107-
'Relay Node "{_type}" not found in schema'.format(_type=_type)
108-
)
104+
raise Exception(f'Relay Node "{_type}" not found in schema')
109105

110106
graphene_type = graphene_type.graphene_type
111107

112108
if only_type:
113-
assert graphene_type == only_type, ("Must receive a {} id.").format(
114-
only_type._meta.name
115-
)
109+
assert (
110+
graphene_type == only_type
111+
), f"Must receive a {only_type._meta.name} id."
116112

117113
# We make sure the ObjectType implements the "Node" interface
118114
if cls not in graphene_type._meta.interfaces:
119115
raise Exception(
120-
'ObjectType "{_type}" does not implement the "{cls}" interface.'.format(
121-
_type=_type, cls=cls
122-
)
116+
f'ObjectType "{_type}" does not implement the "{cls}" interface.'
123117
)
124118

125119
get_node = getattr(graphene_type, "get_node", None)

graphene/relay/tests/test_connection_query.py

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -134,32 +134,28 @@ async def test_respects_an_overly_large_last():
134134

135135
@mark.asyncio
136136
async def test_respects_first_and_after():
137-
await check(
138-
'first: 2, after: "{}"'.format(cursor_for("B")), "CD", has_next_page=True
139-
)
137+
await check(f'first: 2, after: "{cursor_for("B")}"', "CD", has_next_page=True)
140138

141139

142140
@mark.asyncio
143141
async def test_respects_first_and_after_with_long_first():
144-
await check('first: 10, after: "{}"'.format(cursor_for("B")), "CDE")
142+
await check(f'first: 10, after: "{cursor_for("B")}"', "CDE")
145143

146144

147145
@mark.asyncio
148146
async def test_respects_last_and_before():
149-
await check(
150-
'last: 2, before: "{}"'.format(cursor_for("D")), "BC", has_previous_page=True
151-
)
147+
await check(f'last: 2, before: "{cursor_for("D")}"', "BC", has_previous_page=True)
152148

153149

154150
@mark.asyncio
155151
async def test_respects_last_and_before_with_long_last():
156-
await check('last: 10, before: "{}"'.format(cursor_for("D")), "ABC")
152+
await check(f'last: 10, before: "{cursor_for("D")}"', "ABC")
157153

158154

159155
@mark.asyncio
160156
async def test_respects_first_and_after_and_before_too_few():
161157
await check(
162-
'first: 2, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
158+
f'first: 2, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
163159
"BC",
164160
has_next_page=True,
165161
)
@@ -168,23 +164,21 @@ async def test_respects_first_and_after_and_before_too_few():
168164
@mark.asyncio
169165
async def test_respects_first_and_after_and_before_too_many():
170166
await check(
171-
'first: 4, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
172-
"BCD",
167+
f'first: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
173168
)
174169

175170

176171
@mark.asyncio
177172
async def test_respects_first_and_after_and_before_exactly_right():
178173
await check(
179-
'first: 3, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
180-
"BCD",
174+
f'first: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
181175
)
182176

183177

184178
@mark.asyncio
185179
async def test_respects_last_and_after_and_before_too_few():
186180
await check(
187-
'last: 2, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
181+
f'last: 2, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
188182
"CD",
189183
has_previous_page=True,
190184
)
@@ -193,16 +187,14 @@ async def test_respects_last_and_after_and_before_too_few():
193187
@mark.asyncio
194188
async def test_respects_last_and_after_and_before_too_many():
195189
await check(
196-
'last: 4, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
197-
"BCD",
190+
f'last: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
198191
)
199192

200193

201194
@mark.asyncio
202195
async def test_respects_last_and_after_and_before_exactly_right():
203196
await check(
204-
'last: 3, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
205-
"BCD",
197+
f'last: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
206198
)
207199

208200

@@ -219,19 +211,15 @@ async def test_returns_all_elements_if_cursors_are_invalid():
219211
@mark.asyncio
220212
async def test_returns_all_elements_if_cursors_are_on_the_outside():
221213
await check(
222-
'before: "{}" after: "{}"'.format(
223-
base64("arrayconnection:%s" % 6), base64("arrayconnection:%s" % -1)
224-
),
214+
f'before: "{base64("arrayconnection:%s" % 6)}" after: "{base64("arrayconnection:%s" % -1)}"',
225215
"ABCDE",
226216
)
227217

228218

229219
@mark.asyncio
230220
async def test_returns_no_elements_if_cursors_cross():
231221
await check(
232-
'before: "{}" after: "{}"'.format(
233-
base64("arrayconnection:%s" % 2), base64("arrayconnection:%s" % 4)
234-
),
222+
f'before: "{base64("arrayconnection:%s" % 2)}" after: "{base64("arrayconnection:%s" % 4)}"',
235223
"",
236224
)
237225

graphene/types/argument.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,18 +94,17 @@ def to_arguments(args, extra_args=None):
9494

9595
if isinstance(arg, (InputField, Field)):
9696
raise ValueError(
97-
"Expected {} to be Argument, but received {}. Try using Argument({}).".format(
98-
default_name, type(arg).__name__, arg.type
99-
)
97+
f"Expected {default_name} to be Argument, "
98+
f"but received {type(arg).__name__}. Try using Argument({arg.type})."
10099
)
101100

102101
if not isinstance(arg, Argument):
103-
raise ValueError('Unknown argument "{}".'.format(default_name))
102+
raise ValueError(f'Unknown argument "{default_name}".')
104103

105104
arg_name = default_name or arg.name
106105
assert (
107106
arg_name not in arguments
108-
), 'More than one Argument have same name "{}".'.format(arg_name)
107+
), f'More than one Argument have same name "{arg_name}".'
109108
arguments[arg_name] = arg
110109

111110
return arguments

graphene/types/base.py

Lines changed: 2 additions & 2 deletions
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)