Skip to content

Commit 4f9d52b

Browse files
committed
Refactor string .format() to f-string syntax. Minor corrections. Blackened project.
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).
1 parent 40534bc commit 4f9d52b

26 files changed

+123
-148
lines changed

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-31
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"{obj!r} 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 {obj!r} 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 {obj!r}"
175175
raise ValueError(msg)
176176

177-
raise ValueError("callable {!r} is not supported by signature".format(obj))
177+
raise ValueError(f"callable {obj!r} 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: {self._name!r}>"
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"{name!r} 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} {self.name!r}>"
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: {name!r}"
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"{func!r} 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"{param.name!r} 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"{param.name!r} 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 {param.name!r}"
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"{param.name!r} parameter is positional only, "
767+
"but was passed as a keyword"
772768
)
773769

774770
if param.kind == _VAR_KEYWORD:
@@ -789,9 +785,7 @@ def _bind(self, args, kwargs, partial=False):
789785
and param.kind != _VAR_POSITIONAL
790786
and param.default is _empty
791787
):
792-
raise TypeError(
793-
"{arg!r} parameter lacking default value".format(arg=param_name)
794-
)
788+
raise TypeError(f"{param_name!r} parameter lacking default value")
795789

796790
else:
797791
arguments[param_name] = arg_val
@@ -841,10 +835,10 @@ def __str__(self):
841835

842836
result.append(formatted)
843837

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

846840
if self.return_annotation is not _empty:
847841
anno = formatannotation(self.return_annotation)
848-
rendered += " -> {}".format(anno)
842+
rendered += f" -> {anno}"
849843

850844
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
@@ -22,10 +22,10 @@ def __setattr__(self, name, value):
2222
if not self._frozen:
2323
super(BaseOptions, self).__setattr__(name, value)
2424
else:
25-
raise Exception("Can't modify frozen Options {}".format(self))
25+
raise Exception(f"Can't modify frozen Options {self}")
2626

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

3030

3131
class BaseType(SubclassWithMeta):

graphene/types/datetime.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def serialize(date):
2222
date = date.date()
2323
assert isinstance(
2424
date, datetime.date
25-
), 'Received not compatible date "{}"'.format(repr(date))
25+
), f'Received incompatible date "{repr(date)}"'
2626
return date.isoformat()
2727

2828
@classmethod
@@ -52,7 +52,7 @@ class DateTime(Scalar):
5252
def serialize(dt):
5353
assert isinstance(
5454
dt, (datetime.datetime, datetime.date)
55-
), 'Received not compatible datetime "{}"'.format(repr(dt))
55+
), f'Received incompatible datetime "{repr(dt)}"'
5656
return dt.isoformat()
5757

5858
@classmethod
@@ -82,7 +82,7 @@ class Time(Scalar):
8282
def serialize(time):
8383
assert isinstance(
8484
time, datetime.time
85-
), 'Received not compatible time "{}"'.format(repr(time))
85+
), f'Received incompatible time "{repr(time)}"'
8686
return time.isoformat()
8787

8888
@classmethod

graphene/types/decimal.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,7 @@ class Decimal(Scalar):
1616
def serialize(dec):
1717
if isinstance(dec, str):
1818
dec = _Decimal(dec)
19-
assert isinstance(dec, _Decimal), 'Received not compatible Decimal "{}"'.format(
20-
repr(dec)
21-
)
19+
assert isinstance(dec, _Decimal), f'Received incompatible Decimal "{repr(dec)}"'
2220
return str(dec)
2321

2422
@classmethod

0 commit comments

Comments
 (0)