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
This commit is contained in:
Syrus Akbary 2020-03-14 17:32:44 -07:00 committed by GitHub
parent 14183012a8
commit 60a9609b9a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 136 additions and 183 deletions

View File

@ -18,7 +18,7 @@ repos:
hooks:
- id: pyupgrade
- repo: https://github.com/ambv/black
rev: 19.3b0
rev: 19.10b0
hooks:
- id: black
language_version: python3

View File

@ -377,10 +377,7 @@ class Base(ObjectType):
id = ID()
def resolve_id(root, info):
return "{type}_{id}".format(
type=root.__class__.__name__,
id=root.id
)
return f"{root.__class__.__name__}_{root.id}"
```
### UUID Scalar

View File

@ -55,12 +55,9 @@ logs the time it takes to resolve each field
def timing_middleware(next, root, info, **args):
start = timer()
return_value = next(root, info, **args)
duration = timer() - start
logger.debug("{parent_type}.{field_name}: {duration} ms".format(
parent_type=root._meta.name if root and hasattr(root, '_meta') else '',
field_name=info.field_name,
duration=round(duration * 1000, 2)
))
duration = round((timer() - start) * 1000, 2)
parent_type_name = root._meta.name if root and hasattr(root, '_meta') else ''
logger.debug(f"{parent_type_name}.{info.field_name}: {duration} ms")
return return_value

View File

@ -52,7 +52,7 @@ Example of a custom node:
@staticmethod
def to_global_id(type, id):
return '{}:{}'.format(type, id)
return f"{type}:{id}"
@staticmethod
def get_node_from_global_id(info, global_id, only_type=None):

View File

@ -331,7 +331,7 @@ A field can use a custom resolver from outside the class:
from graphene import ObjectType, String
def resolve_full_name(person, info):
return '{} {}'.format(person.first_name, person.last_name)
return f"{person.first_name} {person.last_name}"
class Person(ObjectType):
first_name = String()

View File

@ -7,7 +7,7 @@ class GeoInput(graphene.InputObjectType):
@property
def latlng(self):
return "({},{})".format(self.lat, self.lng)
return f"({self.lat},{self.lng})"
class Address(graphene.ObjectType):

View File

@ -63,16 +63,14 @@ class Connection(ObjectType):
@classmethod
def __init_subclass_with_meta__(cls, node=None, name=None, **options):
_meta = ConnectionOptions(cls)
assert node, "You have to provide a node in {}.Meta".format(cls.__name__)
assert node, f"You have to provide a node in {cls.__name__}.Meta"
assert isinstance(node, NonNull) or issubclass(
node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)
), ('Received incompatible node "{}" for Connection {}.').format(
node, cls.__name__
)
), f'Received incompatible node "{node}" for Connection {cls.__name__}.'
base_name = re.sub("Connection$", "", name or cls.__name__) or node._meta.name
if not name:
name = "{}Connection".format(base_name)
name = f"{base_name}Connection"
edge_class = getattr(cls, "Edge", None)
_node = node
@ -82,11 +80,9 @@ class Connection(ObjectType):
cursor = String(required=True, description="A cursor for use in pagination")
class EdgeMeta:
description = "A Relay edge containing a `{}` and its cursor.".format(
base_name
)
description = f"A Relay edge containing a `{base_name}` and its cursor."
edge_name = "{}Edge".format(base_name)
edge_name = f"{base_name}Edge"
if edge_class:
edge_bases = (edge_class, EdgeBase, ObjectType)
else:
@ -141,9 +137,9 @@ class IterableConnectionField(Field):
"Read more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#node-connections"
)
assert issubclass(connection_type, Connection), (
'{} type has to be a subclass of Connection. Received "{}".'
).format(self.__class__.__name__, connection_type)
assert issubclass(
connection_type, Connection
), f'{self.__class__.__name__} type has to be a subclass of Connection. Received "{connection_type}".'
return type
@classmethod
@ -152,9 +148,9 @@ class IterableConnectionField(Field):
return resolved
assert isinstance(resolved, Iterable), (
"Resolved value from the connection field has to be an iterable or instance of {}. "
'Received "{}"'
).format(connection_type, resolved)
f"Resolved value from the connection field has to be an iterable or instance of {connection_type}. "
f'Received "{resolved}"'
)
connection = connection_from_array(
resolved,
args,

View File

@ -27,7 +27,7 @@ class ClientIDMutation(Mutation):
input_fields = {}
cls.Input = type(
"{}Input".format(base_name),
f"{base_name}Input",
bases,
dict(input_fields, client_mutation_id=String(name="clientMutationId")),
)
@ -39,12 +39,12 @@ class ClientIDMutation(Mutation):
mutate_and_get_payload = getattr(cls, "mutate_and_get_payload", None)
if cls.mutate and cls.mutate.__func__ == ClientIDMutation.mutate.__func__:
assert mutate_and_get_payload, (
"{name}.mutate_and_get_payload method is required"
f"{name or cls.__name__}.mutate_and_get_payload method is required"
" in a ClientIDMutation."
).format(name=name or cls.__name__)
)
if not name:
name = "{}Payload".format(base_name)
name = f"{base_name}Payload"
super(ClientIDMutation, cls).__init_subclass_with_meta__(
output=None, arguments=arguments, name=name, **options
@ -58,9 +58,7 @@ class ClientIDMutation(Mutation):
payload.client_mutation_id = input.get("client_mutation_id")
except Exception:
raise Exception(
("Cannot set client_mutation_id in the payload object {}").format(
repr(payload)
)
f"Cannot set client_mutation_id in the payload object {repr(payload)}"
)
return payload

View File

@ -57,7 +57,7 @@ class NodeField(Field):
# interface
type or node,
id=ID(required=True, description="The ID of the object"),
**kwargs
**kwargs,
)
def get_resolver(self, parent_resolver):
@ -93,33 +93,27 @@ class Node(AbstractNode):
except Exception as e:
raise Exception(
(
'Unable to parse global ID "{global_id}". '
f'Unable to parse global ID "{global_id}". '
'Make sure it is a base64 encoded string in the format: "TypeName:id". '
"Exception message: {exception}".format(
global_id=global_id, exception=str(e)
)
f"Exception message: {str(e)}"
)
)
graphene_type = info.schema.get_type(_type)
if graphene_type is None:
raise Exception(
'Relay Node "{_type}" not found in schema'.format(_type=_type)
)
raise Exception(f'Relay Node "{_type}" not found in schema')
graphene_type = graphene_type.graphene_type
if only_type:
assert graphene_type == only_type, ("Must receive a {} id.").format(
only_type._meta.name
)
assert (
graphene_type == only_type
), f"Must receive a {only_type._meta.name} id."
# We make sure the ObjectType implements the "Node" interface
if cls not in graphene_type._meta.interfaces:
raise Exception(
'ObjectType "{_type}" does not implement the "{cls}" interface.'.format(
_type=_type, cls=cls
)
f'ObjectType "{_type}" does not implement the "{cls}" interface.'
)
get_node = getattr(graphene_type, "get_node", None)

View File

@ -134,32 +134,28 @@ async def test_respects_an_overly_large_last():
@mark.asyncio
async def test_respects_first_and_after():
await check(
'first: 2, after: "{}"'.format(cursor_for("B")), "CD", has_next_page=True
)
await check(f'first: 2, after: "{cursor_for("B")}"', "CD", has_next_page=True)
@mark.asyncio
async def test_respects_first_and_after_with_long_first():
await check('first: 10, after: "{}"'.format(cursor_for("B")), "CDE")
await check(f'first: 10, after: "{cursor_for("B")}"', "CDE")
@mark.asyncio
async def test_respects_last_and_before():
await check(
'last: 2, before: "{}"'.format(cursor_for("D")), "BC", has_previous_page=True
)
await check(f'last: 2, before: "{cursor_for("D")}"', "BC", has_previous_page=True)
@mark.asyncio
async def test_respects_last_and_before_with_long_last():
await check('last: 10, before: "{}"'.format(cursor_for("D")), "ABC")
await check(f'last: 10, before: "{cursor_for("D")}"', "ABC")
@mark.asyncio
async def test_respects_first_and_after_and_before_too_few():
await check(
'first: 2, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
f'first: 2, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
"BC",
has_next_page=True,
)
@ -168,23 +164,21 @@ async def test_respects_first_and_after_and_before_too_few():
@mark.asyncio
async def test_respects_first_and_after_and_before_too_many():
await check(
'first: 4, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
"BCD",
f'first: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
)
@mark.asyncio
async def test_respects_first_and_after_and_before_exactly_right():
await check(
'first: 3, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
"BCD",
f'first: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
)
@mark.asyncio
async def test_respects_last_and_after_and_before_too_few():
await check(
'last: 2, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
f'last: 2, after: "{cursor_for("A")}", before: "{cursor_for("E")}"',
"CD",
has_previous_page=True,
)
@ -193,16 +187,14 @@ async def test_respects_last_and_after_and_before_too_few():
@mark.asyncio
async def test_respects_last_and_after_and_before_too_many():
await check(
'last: 4, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
"BCD",
f'last: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
)
@mark.asyncio
async def test_respects_last_and_after_and_before_exactly_right():
await check(
'last: 3, after: "{}", before: "{}"'.format(cursor_for("A"), cursor_for("E")),
"BCD",
f'last: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
)
@ -219,9 +211,7 @@ async def test_returns_all_elements_if_cursors_are_invalid():
@mark.asyncio
async def test_returns_all_elements_if_cursors_are_on_the_outside():
await check(
'before: "{}" after: "{}"'.format(
base64("arrayconnection:%s" % 6), base64("arrayconnection:%s" % -1)
),
f'before: "{base64("arrayconnection:%s" % 6)}" after: "{base64("arrayconnection:%s" % -1)}"',
"ABCDE",
)
@ -229,9 +219,7 @@ async def test_returns_all_elements_if_cursors_are_on_the_outside():
@mark.asyncio
async def test_returns_no_elements_if_cursors_cross():
await check(
'before: "{}" after: "{}"'.format(
base64("arrayconnection:%s" % 2), base64("arrayconnection:%s" % 4)
),
f'before: "{base64("arrayconnection:%s" % 2)}" after: "{base64("arrayconnection:%s" % 4)}"',
"",
)

View File

@ -94,18 +94,17 @@ def to_arguments(args, extra_args=None):
if isinstance(arg, (InputField, Field)):
raise ValueError(
"Expected {} to be Argument, but received {}. Try using Argument({}).".format(
default_name, type(arg).__name__, arg.type
)
f"Expected {default_name} to be Argument, "
f"but received {type(arg).__name__}. Try using Argument({arg.type})."
)
if not isinstance(arg, Argument):
raise ValueError('Unknown argument "{}".'.format(default_name))
raise ValueError(f'Unknown argument "{default_name}".')
arg_name = default_name or arg.name
assert (
arg_name not in arguments
), 'More than one Argument have same name "{}".'.format(arg_name)
), f'More than one Argument have same name "{arg_name}".'
arguments[arg_name] = arg
return arguments

View File

@ -20,10 +20,10 @@ class BaseOptions:
if not self._frozen:
super(BaseOptions, self).__setattr__(name, value)
else:
raise Exception("Can't modify frozen Options {}".format(self))
raise Exception(f"Can't modify frozen Options {self}")
def __repr__(self):
return "<{} name={}>".format(self.__class__.__name__, repr(self.name))
return f"<{self.__class__.__name__} name={repr(self.name)}>"
class BaseType(SubclassWithMeta):

View File

@ -21,14 +21,14 @@ class Date(Scalar):
if isinstance(date, datetime.datetime):
date = date.date()
if not isinstance(date, datetime.date):
raise GraphQLError("Date cannot represent value: {}".format(repr(date)))
raise GraphQLError(f"Date cannot represent value: {repr(date)}")
return date.isoformat()
@classmethod
def parse_literal(cls, node):
if not isinstance(node, StringValueNode):
raise GraphQLError(
"Date cannot represent non-string value: {}".format(print_ast(node))
f"Date cannot represent non-string value: {print_ast(node)}"
)
return cls.parse_value(node.value)
@ -37,13 +37,11 @@ class Date(Scalar):
if isinstance(value, datetime.date):
return value
if not isinstance(value, str):
raise GraphQLError(
"Date cannot represent non-string value: {}".format(repr(value))
)
raise GraphQLError(f"Date cannot represent non-string value: {repr(value)}")
try:
return parse_date(value)
except ValueError:
raise GraphQLError("Date cannot represent value: {}".format(repr(value)))
raise GraphQLError(f"Date cannot represent value: {repr(value)}")
class DateTime(Scalar):
@ -56,14 +54,14 @@ class DateTime(Scalar):
@staticmethod
def serialize(dt):
if not isinstance(dt, (datetime.datetime, datetime.date)):
raise GraphQLError("DateTime cannot represent value: {}".format(repr(dt)))
raise GraphQLError(f"DateTime cannot represent value: {repr(dt)}")
return dt.isoformat()
@classmethod
def parse_literal(cls, node):
if not isinstance(node, StringValueNode):
raise GraphQLError(
"DateTime cannot represent non-string value: {}".format(print_ast(node))
f"DateTime cannot represent non-string value: {print_ast(node)}"
)
return cls.parse_value(node.value)
@ -73,14 +71,12 @@ class DateTime(Scalar):
return value
if not isinstance(value, str):
raise GraphQLError(
"DateTime cannot represent non-string value: {}".format(repr(value))
f"DateTime cannot represent non-string value: {repr(value)}"
)
try:
return parse_datetime(value)
except ValueError:
raise GraphQLError(
"DateTime cannot represent value: {}".format(repr(value))
)
raise GraphQLError(f"DateTime cannot represent value: {repr(value)}")
class Time(Scalar):
@ -93,14 +89,14 @@ class Time(Scalar):
@staticmethod
def serialize(time):
if not isinstance(time, datetime.time):
raise GraphQLError("Time cannot represent value: {}".format(repr(time)))
raise GraphQLError(f"Time cannot represent value: {repr(time)}")
return time.isoformat()
@classmethod
def parse_literal(cls, node):
if not isinstance(node, StringValueNode):
raise GraphQLError(
"Time cannot represent non-string value: {}".format(print_ast(node))
f"Time cannot represent non-string value: {print_ast(node)}"
)
return cls.parse_value(node.value)
@ -109,10 +105,8 @@ class Time(Scalar):
if isinstance(value, datetime.time):
return value
if not isinstance(value, str):
raise GraphQLError(
"Time cannot represent non-string value: {}".format(repr(value))
)
raise GraphQLError(f"Time cannot represent non-string value: {repr(value)}")
try:
return parse_time(value)
except ValueError:
raise GraphQLError("Time cannot represent value: {}".format(repr(value)))
raise GraphQLError(f"Time cannot represent value: {repr(value)}")

View File

@ -16,9 +16,9 @@ class Decimal(Scalar):
def serialize(dec):
if isinstance(dec, str):
dec = _Decimal(dec)
assert isinstance(dec, _Decimal), 'Received not compatible Decimal "{}"'.format(
repr(dec)
)
assert isinstance(
dec, _Decimal
), f'Received not compatible Decimal "{repr(dec)}"'
return str(dec)
@classmethod

View File

@ -72,18 +72,18 @@ class Field(MountedType):
required=False,
_creation_counter=None,
default_value=None,
**extra_args
**extra_args,
):
super(Field, self).__init__(_creation_counter=_creation_counter)
assert not args or isinstance(args, Mapping), (
'Arguments in a field have to be a mapping, received "{}".'
).format(args)
assert not args or isinstance(
args, Mapping
), f'Arguments in a field have to be a mapping, received "{args}".'
assert not (
source and resolver
), "A Field cannot have a source and a resolver in at the same time."
assert not callable(default_value), (
'The default value can not be a function but received "{}".'
).format(base_type(default_value))
assert not callable(
default_value
), f'The default value can not be a function but received "{base_type(default_value)}".'
if required:
type = NonNull(type)

View File

@ -8,13 +8,13 @@ class MountedType(OrderedType):
"""
Mount the UnmountedType instance
"""
assert isinstance(unmounted, UnmountedType), ("{} can't mount {}").format(
cls.__name__, repr(unmounted)
)
assert isinstance(
unmounted, UnmountedType
), f"{cls.__name__} can't mount {repr(unmounted)}"
return cls(
unmounted.get_type(),
*unmounted.args,
_creation_counter=unmounted.creation_counter,
**unmounted.kwargs
**unmounted.kwargs,
)

View File

@ -72,7 +72,7 @@ class Mutation(ObjectType):
output=None,
arguments=None,
_meta=None,
**options
**options,
):
if not _meta:
_meta = MutationOptions(cls)
@ -81,9 +81,9 @@ class Mutation(ObjectType):
fields = {}
for interface in interfaces:
assert issubclass(interface, Interface), (
'All interfaces of {} must be a subclass of Interface. Received "{}".'
).format(cls.__name__, interface)
assert issubclass(
interface, Interface
), f'All interfaces of {cls.__name__} must be a subclass of Interface. Received "{interface}".'
fields.update(interface._meta.fields)
if not output:
@ -100,11 +100,11 @@ class Mutation(ObjectType):
if input_class:
warn_deprecation(
(
"Please use {name}.Arguments instead of {name}.Input."
f"Please use {cls.__name__}.Arguments instead of {cls.__name__}.Input."
" Input is now only used in ClientMutationID.\n"
"Read more:"
" https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#mutation-input"
).format(name=cls.__name__)
)
)
if input_class:

View File

@ -93,7 +93,7 @@ class ObjectType(BaseType):
possible_types=(),
default_resolver=None,
_meta=None,
**options
**options,
):
if not _meta:
_meta = ObjectTypeOptions(cls)
@ -101,18 +101,18 @@ class ObjectType(BaseType):
fields = {}
for interface in interfaces:
assert issubclass(interface, Interface), (
'All interfaces of {} must be a subclass of Interface. Received "{}".'
).format(cls.__name__, interface)
assert issubclass(
interface, Interface
), f'All interfaces of {cls.__name__} must be a subclass of Interface. Received "{interface}".'
fields.update(interface._meta.fields)
for base in reversed(cls.__mro__):
fields.update(yank_fields_from_attrs(base.__dict__, _as=Field))
assert not (possible_types and cls.is_type_of), (
"{name}.Meta.possible_types will cause type collision with {name}.is_type_of. "
f"{cls.__name__}.Meta.possible_types will cause type collision with {cls.__name__}.is_type_of. "
"Please use one or other."
).format(name=cls.__name__)
)
if _meta.fields:
_meta.fields.update(fields)
@ -165,7 +165,6 @@ class ObjectType(BaseType):
pass
if kwargs:
raise TypeError(
"'{}' is an invalid keyword argument for {}".format(
list(kwargs)[0], self.__class__.__name__
)
f"'{list(kwargs)[0]}' is an invalid keyword argument"
f" for {self.__class__.__name__}"
)

View File

@ -58,9 +58,9 @@ def assert_valid_root_type(type_):
return
is_graphene_objecttype = inspect.isclass(type_) and issubclass(type_, ObjectType)
is_graphql_objecttype = isinstance(type_, GraphQLObjectType)
assert is_graphene_objecttype or is_graphql_objecttype, (
"Type {} is not a valid ObjectType."
).format(type_)
assert (
is_graphene_objecttype or is_graphql_objecttype
), f"Type {type_} is not a valid ObjectType."
def is_graphene_type(type_):
@ -113,9 +113,7 @@ class TypeMap(dict):
try:
name = graphene_type._meta.name
except AttributeError:
raise TypeError(
"Expected Graphene type, but received: {}.".format(graphene_type)
)
raise TypeError(f"Expected Graphene type, but received: {graphene_type}.")
graphql_type = self.get(name)
if graphql_type:
return graphql_type
@ -132,9 +130,7 @@ class TypeMap(dict):
elif issubclass(graphene_type, Union):
graphql_type = self.construct_union(graphene_type)
else:
raise TypeError(
"Expected Graphene type, but received: {}.".format(graphene_type)
)
raise TypeError(f"Expected Graphene type, but received: {graphene_type}.")
self[name] = graphql_type
return graphql_type
@ -316,12 +312,15 @@ class TypeMap(dict):
args=args,
resolve=field.get_resolver(
self.get_resolver_for_type(
graphene_type, "resolve_{}", name, field.default_value
graphene_type, f"resolve_{name}", name, field.default_value
)
),
subscribe=field.get_resolver(
self.get_resolver_for_type(
graphene_type, "subscribe_{}", name, field.default_value
graphene_type,
f"subscribe_{name}",
name,
field.default_value,
)
),
deprecation_reason=field.deprecation_reason,
@ -331,10 +330,9 @@ class TypeMap(dict):
fields[field_name] = _field
return fields
def get_resolver_for_type(self, graphene_type, pattern, name, default_value):
def get_resolver_for_type(self, graphene_type, func_name, name, default_value):
if not issubclass(graphene_type, ObjectType):
return
func_name = pattern.format(name)
resolver = getattr(graphene_type, func_name, None)
if not resolver:
# If we don't find the resolver in the ObjectType class, then try to
@ -366,10 +364,10 @@ class TypeMap(dict):
if inspect.isclass(type_) and issubclass(type_, ObjectType):
graphql_type = self.get(type_._meta.name)
assert graphql_type, "Can't find type {} in schema".format(type_._meta.name)
assert graphql_type.graphene_type == type_, (
"The type {} does not match with the associated graphene type {}."
).format(type_, graphql_type.graphene_type)
assert graphql_type, f"Can't find type {type_._meta.name} in schema"
assert (
graphql_type.graphene_type == type_
), f"The type {type_} does not match with the associated graphene type {graphql_type.graphene_type}."
return graphql_type
return type_
@ -377,7 +375,7 @@ class TypeMap(dict):
def get_resolver(self, graphene_type, name, default_value):
if not issubclass(graphene_type, ObjectType):
return
resolver = getattr(graphene_type, "resolve_{}".format(name), None)
resolver = getattr(graphene_type, f"resolve_{name}", None)
if not resolver:
# If we don't find the resolver in the ObjectType class, then try to
# find it in each of the interfaces
@ -385,7 +383,7 @@ class TypeMap(dict):
for interface in graphene_type._meta.interfaces:
if name not in interface._meta.fields:
continue
interface_resolver = getattr(interface, "resolve_{}".format(name), None)
interface_resolver = getattr(interface, f"resolve_{name}", None)
if interface_resolver:
break
resolver = interface_resolver
@ -458,7 +456,7 @@ class Schema:
"""
_type = self.graphql_schema.get_type(type_name)
if _type is None:
raise AttributeError('Type "{}" not found in the Schema'.format(type_name))
raise AttributeError(f'Type "{type_name}" not found in the Schema')
if isinstance(_type, GrapheneGraphQLType):
return _type.graphene_type
return _type

View File

@ -14,9 +14,8 @@ class Structure(UnmountedType):
cls_name = type(self).__name__
of_type_name = type(of_type).__name__
raise Exception(
"{} could not have a mounted {}() as inner type. Try with {}({}).".format(
cls_name, of_type_name, cls_name, of_type_name
)
f"{cls_name} could not have a mounted {of_type_name}()"
f" as inner type. Try with {cls_name}({of_type_name})."
)
self._of_type = of_type
@ -50,7 +49,7 @@ class List(Structure):
"""
def __str__(self):
return "[{}]".format(self.of_type)
return f"[{self.of_type}]"
def __eq__(self, other):
return isinstance(other, List) and (
@ -85,12 +84,12 @@ class NonNull(Structure):
def __init__(self, *args, **kwargs):
super(NonNull, self).__init__(*args, **kwargs)
assert not isinstance(self._of_type, NonNull), (
"Can only create NonNull of a Nullable GraphQLType but got: {}."
).format(self._of_type)
assert not isinstance(
self._of_type, NonNull
), f"Can only create NonNull of a Nullable GraphQLType but got: {self._of_type}."
def __str__(self):
return "{}!".format(self.of_type)
return f"{self.of_type}!"
def __eq__(self, other):
return isinstance(other, NonNull) and (

View File

@ -180,9 +180,7 @@ def test_time_query_variable(sample_time):
def test_bad_variables(sample_date, sample_datetime, sample_time):
def _test_bad_variables(type_, input_):
result = schema.execute(
"""query Test($input: {}){{ {}(in: $input) }}""".format(
type_, type_.lower()
),
f"""query Test($input: {type_}){{ {type_.lower()}(in: $input) }}""",
variables={"input": input_},
)
assert isinstance(result.errors, list)

View File

@ -15,7 +15,7 @@ def test_enum_construction():
@property
def description(self):
return "Description {}".format(self.name)
return f"Description {self.name}"
assert RGB._meta.name == "RGB"
assert RGB._meta.description == "Description"

View File

@ -112,7 +112,7 @@ def test_inputobjecttype_of_input():
@property
def full_name(self):
return "{} {}".format(self.first_name, self.last_name)
return f"{self.first_name} {self.last_name}"
class Parent(InputObjectType):
child = InputField(Child)

View File

@ -454,15 +454,15 @@ def test_query_annotated_resolvers():
info = String()
def resolve_annotated(self, info, id):
return "{}-{}".format(self, id)
return f"{self}-{id}"
def resolve_context(self, info):
assert isinstance(info.context, Context)
return "{}-{}".format(self, info.context.key)
return f"{self}-{info.context.key}"
def resolve_info(self, info):
assert isinstance(info, ResolveInfo)
return "{}-{}".format(self, info.field_name)
return f"{self}-{info.field_name}"
test_schema = Schema(Query)

View File

@ -37,7 +37,7 @@ def test_enum():
@property
def description(self):
return "Description {}={}".format(self.name, self.value)
return f"Description {self.name}={self.value}"
@property
def deprecation_reason(self):

View File

@ -53,7 +53,7 @@ class Union(UnmountedType, BaseType):
def __init_subclass_with_meta__(cls, types=None, **options):
assert (
isinstance(types, (list, tuple)) and len(types) > 0
), "Must provide types for Union {name}.".format(name=cls.__name__)
), f"Must provide types for Union {cls.__name__}."
_meta = UnionOptions(cls)
_meta.types = types

View File

@ -49,7 +49,7 @@ class UnmountedType(OrderedType):
This function is called when the UnmountedType instance
is mounted (as a Field, InputField or Argument)
"""
raise NotImplementedError("get_type not implemented in {}".format(self))
raise NotImplementedError(f"get_type not implemented in {self}")
def mount_as(self, _as):
return _as.mounted(self)

View File

@ -17,9 +17,7 @@ class UUID(Scalar):
if isinstance(uuid, str):
uuid = _UUID(uuid)
assert isinstance(uuid, _UUID), "Expected UUID instance, received {}".format(
uuid
)
assert isinstance(uuid, _UUID), f"Expected UUID instance, received {uuid}"
return str(uuid)
@staticmethod

View File

@ -2,7 +2,7 @@ import functools
import inspect
import warnings
string_types = (type(b""), type(u""))
string_types = (type(b""), type(""))
def warn_deprecation(text):
@ -29,13 +29,13 @@ def deprecated(reason):
def decorator(func1):
if inspect.isclass(func1):
fmt1 = "Call to deprecated class {name} ({reason})."
fmt1 = f"Call to deprecated class {func1.__name__} ({reason})."
else:
fmt1 = "Call to deprecated function {name} ({reason})."
fmt1 = f"Call to deprecated function {func1.__name__} ({reason})."
@functools.wraps(func1)
def new_func1(*args, **kwargs):
warn_deprecation(fmt1.format(name=func1.__name__, reason=reason))
warn_deprecation(fmt1)
return func1(*args, **kwargs)
return new_func1
@ -55,13 +55,13 @@ def deprecated(reason):
func2 = reason
if inspect.isclass(func2):
fmt2 = "Call to deprecated class {name}."
fmt2 = f"Call to deprecated class {func2.__name__}."
else:
fmt2 = "Call to deprecated function {name}."
fmt2 = f"Call to deprecated function {func2.__name__}."
@functools.wraps(func2)
def new_func2(*args, **kwargs):
warn_deprecation(fmt2.format(name=func2.__name__))
warn_deprecation(fmt2)
return func2(*args, **kwargs)
return new_func2

View File

@ -12,7 +12,7 @@ class SubclassWithMeta_Meta(type):
return cls.__name__
def __repr__(cls):
return "<{} meta={}>".format(cls.__name__, repr(cls._meta))
return f"<{cls.__name__} meta={repr(cls._meta)}>"
class SubclassWithMeta(metaclass=SubclassWithMeta_Meta):
@ -29,9 +29,7 @@ class SubclassWithMeta(metaclass=SubclassWithMeta_Meta):
_meta_props = props(_Meta)
else:
raise Exception(
"Meta have to be either a class or a dict. Received {}".format(
_Meta
)
f"Meta have to be either a class or a dict. Received {_Meta}"
)
delattr(cls, "Meta")
options = dict(meta_options, **_meta_props)
@ -40,8 +38,8 @@ class SubclassWithMeta(metaclass=SubclassWithMeta_Meta):
if abstract:
assert not options, (
"Abstract types can only contain the abstract attribute. "
"Received: abstract, {option_keys}"
).format(option_keys=", ".join(options))
f"Received: abstract, {', '.join(options)}"
)
else:
super_class = super(cls, cls)
if hasattr(super_class, "__init_subclass_with_meta__"):