Skip to content

Commit a22b09c

Browse files
committed
Updated all str.format(…) to f-strings
This revamps the PR #984
1 parent 1418301 commit a22b09c

29 files changed

+109
-144
lines changed

UPGRADE-v2.0.md

+1-4
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

+3-6
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

+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

+1-1
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

+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/relay/connection.py

+10-14
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:
@@ -142,8 +138,8 @@ def type(self):
142138
)
143139

144140
assert issubclass(connection_type, Connection), (
145-
'{} type has to be a subclass of Connection. Received "{}".'
146-
).format(self.__class__.__name__, connection_type)
141+
f"{self.__class__.__name__} type has to be a subclass of Connection. Received \"{connection_type}\"."
142+
)
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

+5-7
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

+6-10
Original file line numberDiff line numberDiff line change
@@ -93,33 +93,29 @@ 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:
106104
raise Exception(
107-
'Relay Node "{_type}" not found in schema'.format(_type=_type)
105+
f"Relay Node \"{_type}\" not found in schema"
108106
)
109107

110108
graphene_type = graphene_type.graphene_type
111109

112110
if only_type:
113-
assert graphene_type == only_type, ("Must receive a {} id.").format(
114-
only_type._meta.name
111+
assert graphene_type == only_type, (
112+
f"Must receive a {only_type._meta.name} id."
115113
)
116114

117115
# We make sure the ObjectType implements the "Node" interface
118116
if cls not in graphene_type._meta.interfaces:
119117
raise Exception(
120-
'ObjectType "{_type}" does not implement the "{cls}" interface.'.format(
121-
_type=_type, cls=cls
122-
)
118+
f"ObjectType \"{_type}\" does not implement the \"{cls}\" interface."
123119
)
124120

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

graphene/relay/tests/test_connection_query.py

+12-16
Original file line numberDiff line numberDiff line change
@@ -135,31 +135,31 @@ async def test_respects_an_overly_large_last():
135135
@mark.asyncio
136136
async def test_respects_first_and_after():
137137
await check(
138-
'first: 2, after: "{}"'.format(cursor_for("B")), "CD", has_next_page=True
138+
f'first: 2, after: \"{cursor_for("B")}\"', "CD", has_next_page=True
139139
)
140140

141141

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

146146

147147
@mark.asyncio
148148
async def test_respects_last_and_before():
149149
await check(
150-
'last: 2, before: "{}"'.format(cursor_for("D")), "BC", has_previous_page=True
150+
f'last: 2, before: "{cursor_for("D")}"', "BC", has_previous_page=True
151151
)
152152

153153

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

158158

159159
@mark.asyncio
160160
async def test_respects_first_and_after_and_before_too_few():
161161
await check(
162-
'first: 2, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
162+
f'first: 2, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
163163
"BC",
164164
has_next_page=True,
165165
)
@@ -168,23 +168,23 @@ async def test_respects_first_and_after_and_before_too_few():
168168
@mark.asyncio
169169
async def test_respects_first_and_after_and_before_too_many():
170170
await check(
171-
'first: 4, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
171+
f'first: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
172172
"BCD",
173173
)
174174

175175

176176
@mark.asyncio
177177
async def test_respects_first_and_after_and_before_exactly_right():
178178
await check(
179-
'first: 3, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
179+
f'first: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
180180
"BCD",
181181
)
182182

183183

184184
@mark.asyncio
185185
async def test_respects_last_and_after_and_before_too_few():
186186
await check(
187-
'last: 2, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
187+
f'last: 2, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
188188
"CD",
189189
has_previous_page=True,
190190
)
@@ -193,15 +193,15 @@ async def test_respects_last_and_after_and_before_too_few():
193193
@mark.asyncio
194194
async def test_respects_last_and_after_and_before_too_many():
195195
await check(
196-
'last: 4, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
196+
f'last: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
197197
"BCD",
198198
)
199199

200200

201201
@mark.asyncio
202202
async def test_respects_last_and_after_and_before_exactly_right():
203203
await check(
204-
'last: 3, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
204+
f'last: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
205205
"BCD",
206206
)
207207

@@ -219,19 +219,15 @@ async def test_returns_all_elements_if_cursors_are_invalid():
219219
@mark.asyncio
220220
async def test_returns_all_elements_if_cursors_are_on_the_outside():
221221
await check(
222-
'before: "{}" after: "{}"'.format(
223-
base64("arrayconnection:%s" % 6), base64("arrayconnection:%s" % -1)
224-
),
222+
f'before: "{base64("arrayconnection:%s" % 6)}" after: "{base64("arrayconnection:%s" % -1)}"',
225223
"ABCDE",
226224
)
227225

228226

229227
@mark.asyncio
230228
async def test_returns_no_elements_if_cursors_cross():
231229
await check(
232-
'before: "{}" after: "{}"'.format(
233-
base64("arrayconnection:%s" % 2), base64("arrayconnection:%s" % 4)
234-
),
230+
f'before: "{base64("arrayconnection:%s" % 2)}" after: "{base64("arrayconnection:%s" % 4)}"',
235231
"",
236232
)
237233

graphene/types/argument.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -94,18 +94,16 @@ 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, but received {type(arg).__name__}. Try using Argument({arg.type})."
10098
)
10199

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

105103
arg_name = default_name or arg.name
106104
assert (
107105
arg_name not in arguments
108-
), 'More than one Argument have same name "{}".'.format(arg_name)
106+
), f'More than one Argument have same name "{arg_name}".'
109107
arguments[arg_name] = arg
110108

111109
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)