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: hooks:
- id: pyupgrade - id: pyupgrade
- repo: https://github.com/ambv/black - repo: https://github.com/ambv/black
rev: 19.3b0 rev: 19.10b0
hooks: hooks:
- id: black - id: black
language_version: python3 language_version: python3

View File

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

View File

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

View File

@ -52,7 +52,7 @@ Example of a custom node:
@staticmethod @staticmethod
def to_global_id(type, id): def to_global_id(type, id):
return '{}:{}'.format(type, id) return f"{type}:{id}"
@staticmethod @staticmethod
def get_node_from_global_id(info, global_id, only_type=None): 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 from graphene import ObjectType, String
def resolve_full_name(person, info): 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): class Person(ObjectType):
first_name = String() first_name = String()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -94,18 +94,17 @@ def to_arguments(args, extra_args=None):
if isinstance(arg, (InputField, Field)): if isinstance(arg, (InputField, Field)):
raise ValueError( raise ValueError(
"Expected {} to be Argument, but received {}. Try using Argument({}).".format( f"Expected {default_name} to be Argument, "
default_name, type(arg).__name__, arg.type f"but received {type(arg).__name__}. Try using Argument({arg.type})."
)
) )
if not isinstance(arg, Argument): 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 arg_name = default_name or arg.name
assert ( assert (
arg_name not in arguments 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 arguments[arg_name] = arg
return arguments return arguments

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -14,9 +14,8 @@ class Structure(UnmountedType):
cls_name = type(self).__name__ cls_name = type(self).__name__
of_type_name = type(of_type).__name__ of_type_name = type(of_type).__name__
raise Exception( raise Exception(
"{} could not have a mounted {}() as inner type. Try with {}({}).".format( f"{cls_name} could not have a mounted {of_type_name}()"
cls_name, of_type_name, cls_name, of_type_name f" as inner type. Try with {cls_name}({of_type_name})."
)
) )
self._of_type = of_type self._of_type = of_type
@ -50,7 +49,7 @@ class List(Structure):
""" """
def __str__(self): def __str__(self):
return "[{}]".format(self.of_type) return f"[{self.of_type}]"
def __eq__(self, other): def __eq__(self, other):
return isinstance(other, List) and ( return isinstance(other, List) and (
@ -85,12 +84,12 @@ class NonNull(Structure):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(NonNull, self).__init__(*args, **kwargs) super(NonNull, self).__init__(*args, **kwargs)
assert not isinstance(self._of_type, NonNull), ( assert not isinstance(
"Can only create NonNull of a Nullable GraphQLType but got: {}." self._of_type, NonNull
).format(self._of_type) ), f"Can only create NonNull of a Nullable GraphQLType but got: {self._of_type}."
def __str__(self): def __str__(self):
return "{}!".format(self.of_type) return f"{self.of_type}!"
def __eq__(self, other): def __eq__(self, other):
return isinstance(other, NonNull) and ( 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(sample_date, sample_datetime, sample_time):
def _test_bad_variables(type_, input_): def _test_bad_variables(type_, input_):
result = schema.execute( result = schema.execute(
"""query Test($input: {}){{ {}(in: $input) }}""".format( f"""query Test($input: {type_}){{ {type_.lower()}(in: $input) }}""",
type_, type_.lower()
),
variables={"input": input_}, variables={"input": input_},
) )
assert isinstance(result.errors, list) assert isinstance(result.errors, list)

View File

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

View File

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

View File

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

View File

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

View File

@ -53,7 +53,7 @@ class Union(UnmountedType, BaseType):
def __init_subclass_with_meta__(cls, types=None, **options): def __init_subclass_with_meta__(cls, types=None, **options):
assert ( assert (
isinstance(types, (list, tuple)) and len(types) > 0 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 = UnionOptions(cls)
_meta.types = types _meta.types = types

View File

@ -49,7 +49,7 @@ class UnmountedType(OrderedType):
This function is called when the UnmountedType instance This function is called when the UnmountedType instance
is mounted (as a Field, InputField or Argument) 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): def mount_as(self, _as):
return _as.mounted(self) return _as.mounted(self)

View File

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

View File

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

View File

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