From a22b09c621ac057b6c4ec71e88da3e0d20b4e44c Mon Sep 17 00:00:00 2001 From: Syrus Date: Sat, 14 Mar 2020 17:23:38 -0700 Subject: [PATCH] =?UTF-8?q?Updated=20all=20str.format(=E2=80=A6)=20to=20f-?= =?UTF-8?q?strings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This revamps the PR #984 --- UPGRADE-v2.0.md | 5 +--- docs/execution/middleware.rst | 9 ++---- docs/relay/nodes.rst | 2 +- docs/types/objecttypes.rst | 2 +- examples/complex_example.py | 2 +- graphene/relay/connection.py | 24 +++++++--------- graphene/relay/mutation.py | 12 ++++---- graphene/relay/node.py | 16 ++++------- graphene/relay/tests/test_connection_query.py | 28 ++++++++----------- graphene/types/argument.py | 8 ++---- graphene/types/base.py | 4 +-- graphene/types/datetime.py | 24 ++++++++-------- graphene/types/decimal.py | 4 +-- graphene/types/field.py | 8 +++--- graphene/types/mountedtype.py | 4 +-- graphene/types/mutation.py | 8 +++--- graphene/types/objecttype.py | 8 +++--- graphene/types/schema.py | 27 +++++++++--------- graphene/types/structures.py | 12 ++++---- graphene/types/tests/test_datetime.py | 4 +-- graphene/types/tests/test_enum.py | 2 +- graphene/types/tests/test_inputobjecttype.py | 2 +- graphene/types/tests/test_query.py | 6 ++-- graphene/types/tests/test_type_map.py | 2 +- graphene/types/union.py | 2 +- graphene/types/unmountedtype.py | 2 +- graphene/types/uuid.py | 4 +-- graphene/utils/deprecated.py | 12 ++++---- graphene/utils/subclass_with_meta.py | 10 +++---- 29 files changed, 109 insertions(+), 144 deletions(-) diff --git a/UPGRADE-v2.0.md b/UPGRADE-v2.0.md index fed15923b..63f8f622f 100644 --- a/UPGRADE-v2.0.md +++ b/UPGRADE-v2.0.md @@ -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 diff --git a/docs/execution/middleware.rst b/docs/execution/middleware.rst index 2a5e20f7a..0c5458b20 100644 --- a/docs/execution/middleware.rst +++ b/docs/execution/middleware.rst @@ -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 diff --git a/docs/relay/nodes.rst b/docs/relay/nodes.rst index 7af00ea1e..ce9bc7d8c 100644 --- a/docs/relay/nodes.rst +++ b/docs/relay/nodes.rst @@ -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): diff --git a/docs/types/objecttypes.rst b/docs/types/objecttypes.rst index 77ab130b0..984acbf06 100644 --- a/docs/types/objecttypes.rst +++ b/docs/types/objecttypes.rst @@ -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() diff --git a/examples/complex_example.py b/examples/complex_example.py index 3c2d77ba2..aaa48a4c3 100644 --- a/examples/complex_example.py +++ b/examples/complex_example.py @@ -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): diff --git a/graphene/relay/connection.py b/graphene/relay/connection.py index 8581a4b5e..7fd8356b9 100644 --- a/graphene/relay/connection.py +++ b/graphene/relay/connection.py @@ -63,16 +63,14 @@ class Meta: @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 EdgeBase: 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: @@ -142,8 +138,8 @@ def type(self): ) assert issubclass(connection_type, Connection), ( - '{} type has to be a subclass of Connection. Received "{}".' - ).format(self.__class__.__name__, connection_type) + f"{self.__class__.__name__} type has to be a subclass of Connection. Received \"{connection_type}\"." + ) return type @classmethod @@ -152,9 +148,9 @@ def resolve_connection(cls, connection_type, args, resolved): 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, diff --git a/graphene/relay/mutation.py b/graphene/relay/mutation.py index fce0c5982..2f4a4b738 100644 --- a/graphene/relay/mutation.py +++ b/graphene/relay/mutation.py @@ -27,7 +27,7 @@ def __init_subclass_with_meta__( 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 @@ def __init_subclass_with_meta__( 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 @@ def on_resolve(payload): 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 diff --git a/graphene/relay/node.py b/graphene/relay/node.py index f8927ab76..e7159cd06 100644 --- a/graphene/relay/node.py +++ b/graphene/relay/node.py @@ -93,33 +93,29 @@ def get_node_from_global_id(cls, info, global_id, only_type=None): 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) + 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) diff --git a/graphene/relay/tests/test_connection_query.py b/graphene/relay/tests/test_connection_query.py index e109067ba..cf75c09d9 100644 --- a/graphene/relay/tests/test_connection_query.py +++ b/graphene/relay/tests/test_connection_query.py @@ -135,31 +135,31 @@ 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 + 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 + 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,7 +168,7 @@ 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")), + f'first: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD", ) @@ -176,7 +176,7 @@ async def test_respects_first_and_after_and_before_too_many(): @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")), + f'first: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD", ) @@ -184,7 +184,7 @@ async def test_respects_first_and_after_and_before_exactly_right(): @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,7 +193,7 @@ 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")), + f'last: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD", ) @@ -201,7 +201,7 @@ async def test_respects_last_and_after_and_before_too_many(): @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")), + f'last: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD", ) @@ -219,9 +219,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 +227,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)}"', "", ) diff --git a/graphene/types/argument.py b/graphene/types/argument.py index cdc21d4bb..bb78339e9 100644 --- a/graphene/types/argument.py +++ b/graphene/types/argument.py @@ -94,18 +94,16 @@ 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, 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 diff --git a/graphene/types/base.py b/graphene/types/base.py index 79907b4d9..29d60fef1 100644 --- a/graphene/types/base.py +++ b/graphene/types/base.py @@ -20,10 +20,10 @@ def __setattr__(self, name, value): 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): diff --git a/graphene/types/datetime.py b/graphene/types/datetime.py index c152668f7..9d95bed93 100644 --- a/graphene/types/datetime.py +++ b/graphene/types/datetime.py @@ -21,14 +21,14 @@ def serialize(date): 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) @@ -38,12 +38,12 @@ def parse_value(value): return value if not isinstance(value, str): raise GraphQLError( - "Date cannot represent non-string value: {}".format(repr(value)) + 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 +56,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,13 +73,13 @@ def parse_value(value): 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)) + f"DateTime cannot represent value: {repr(value)}" ) @@ -93,14 +93,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) @@ -110,9 +110,9 @@ def parse_value(cls, value): return value if not isinstance(value, str): raise GraphQLError( - "Time cannot represent non-string value: {}".format(repr(value)) + 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)}") diff --git a/graphene/types/decimal.py b/graphene/types/decimal.py index 10a2609a9..8895a9169 100644 --- a/graphene/types/decimal.py +++ b/graphene/types/decimal.py @@ -16,9 +16,7 @@ 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 diff --git a/graphene/types/field.py b/graphene/types/field.py index 56c2ff671..9bc36afb0 100644 --- a/graphene/types/field.py +++ b/graphene/types/field.py @@ -76,14 +76,14 @@ def __init__( ): 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) + 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)) + f'The default value can not be a function but received "{base_type(default_value)}".' + ) if required: type = NonNull(type) diff --git a/graphene/types/mountedtype.py b/graphene/types/mountedtype.py index 6d0c8cf85..3e88662de 100644 --- a/graphene/types/mountedtype.py +++ b/graphene/types/mountedtype.py @@ -8,9 +8,7 @@ def mounted(cls, unmounted): # noqa: N802 """ 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(), diff --git a/graphene/types/mutation.py b/graphene/types/mutation.py index 0710d66f4..ad7d34c4e 100644 --- a/graphene/types/mutation.py +++ b/graphene/types/mutation.py @@ -82,8 +82,8 @@ def __init_subclass_with_meta__( for interface in interfaces: assert issubclass(interface, Interface), ( - 'All interfaces of {} must be a subclass of Interface. Received "{}".' - ).format(cls.__name__, 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 @@ def __init_subclass_with_meta__( 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: diff --git a/graphene/types/objecttype.py b/graphene/types/objecttype.py index cca23d111..7ccf09fa5 100644 --- a/graphene/types/objecttype.py +++ b/graphene/types/objecttype.py @@ -102,17 +102,17 @@ def __init_subclass_with_meta__( for interface in interfaces: assert issubclass(interface, Interface), ( - 'All interfaces of {} must be a subclass of Interface. Received "{}".' - ).format(cls.__name__, 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) diff --git a/graphene/types/schema.py b/graphene/types/schema.py index 5228fb44c..dc1b08cc7 100644 --- a/graphene/types/schema.py +++ b/graphene/types/schema.py @@ -59,8 +59,8 @@ def assert_valid_root_type(type_): 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_) + f"Type {type_} is not a valid ObjectType." + ) def is_graphene_type(type_): @@ -114,7 +114,7 @@ def add_type(self, graphene_type): name = graphene_type._meta.name except AttributeError: raise TypeError( - "Expected Graphene type, but received: {}.".format(graphene_type) + f"Expected Graphene type, but received: {graphene_type}." ) graphql_type = self.get(name) if graphql_type: @@ -133,7 +133,7 @@ def add_type(self, graphene_type): graphql_type = self.construct_union(graphene_type) else: raise TypeError( - "Expected Graphene type, but received: {}.".format(graphene_type) + f"Expected Graphene type, but received: {graphene_type}." ) self[name] = graphql_type return graphql_type @@ -316,12 +316,12 @@ def create_fields_for_type(self, graphene_type, is_input_type=False): 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 +331,9 @@ def create_fields_for_type(self, graphene_type, is_input_type=False): 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 +365,10 @@ def resolve_type(self, resolve_type_func, type_name, root, info, _type): 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, f"Can't find type {type_._meta.name} in schema" assert graphql_type.graphene_type == type_, ( - "The type {} does not match with the associated graphene 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 type_ @@ -377,7 +376,7 @@ def resolve_type(self, resolve_type_func, type_name, root, info, _type): 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 +384,7 @@ def get_resolver(self, graphene_type, name, default_value): 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 +457,7 @@ def __getattr__(self, type_name): """ _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 diff --git a/graphene/types/structures.py b/graphene/types/structures.py index 3341e0227..94b3c8e30 100644 --- a/graphene/types/structures.py +++ b/graphene/types/structures.py @@ -14,9 +14,7 @@ def __init__(self, of_type, *args, **kwargs): 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}() as inner type. Try with {cls_name}({of_type_name})." ) self._of_type = of_type @@ -50,7 +48,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 ( @@ -86,11 +84,11 @@ 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) + 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 ( diff --git a/graphene/types/tests/test_datetime.py b/graphene/types/tests/test_datetime.py index 8bc20a41f..6a3241a17 100644 --- a/graphene/types/tests/test_datetime.py +++ b/graphene/types/tests/test_datetime.py @@ -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) diff --git a/graphene/types/tests/test_enum.py b/graphene/types/tests/test_enum.py index 40cd4afd7..1b6181208 100644 --- a/graphene/types/tests/test_enum.py +++ b/graphene/types/tests/test_enum.py @@ -15,7 +15,7 @@ class RGB(Enum): @property def description(self): - return "Description {}".format(self.name) + return f"Description {self.name}" assert RGB._meta.name == "RGB" assert RGB._meta.description == "Description" diff --git a/graphene/types/tests/test_inputobjecttype.py b/graphene/types/tests/test_inputobjecttype.py index e11823823..0fb7e3945 100644 --- a/graphene/types/tests/test_inputobjecttype.py +++ b/graphene/types/tests/test_inputobjecttype.py @@ -112,7 +112,7 @@ class Child(InputObjectType): @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) diff --git a/graphene/types/tests/test_query.py b/graphene/types/tests/test_query.py index fe9f39fce..2d3e4c730 100644 --- a/graphene/types/tests/test_query.py +++ b/graphene/types/tests/test_query.py @@ -454,15 +454,15 @@ class Query(ObjectType): 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) diff --git a/graphene/types/tests/test_type_map.py b/graphene/types/tests/test_type_map.py index 2dbbe6bbb..334eb2415 100644 --- a/graphene/types/tests/test_type_map.py +++ b/graphene/types/tests/test_type_map.py @@ -37,7 +37,7 @@ class MyEnum(Enum): @property def description(self): - return "Description {}={}".format(self.name, self.value) + return f"Description {self.name}={self.value}" @property def deprecation_reason(self): diff --git a/graphene/types/union.py b/graphene/types/union.py index 5ae54562a..928656ae8 100644 --- a/graphene/types/union.py +++ b/graphene/types/union.py @@ -53,7 +53,7 @@ class Query(ObjectType): 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 diff --git a/graphene/types/unmountedtype.py b/graphene/types/unmountedtype.py index 081c4ba00..83a6afefc 100644 --- a/graphene/types/unmountedtype.py +++ b/graphene/types/unmountedtype.py @@ -49,7 +49,7 @@ def get_type(self): 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) diff --git a/graphene/types/uuid.py b/graphene/types/uuid.py index ef09ae6c7..c21eb1658 100644 --- a/graphene/types/uuid.py +++ b/graphene/types/uuid.py @@ -17,9 +17,7 @@ def serialize(uuid): 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 diff --git a/graphene/utils/deprecated.py b/graphene/utils/deprecated.py index 2f98d8296..fcbe8e0c7 100644 --- a/graphene/utils/deprecated.py +++ b/graphene/utils/deprecated.py @@ -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 new_func1(*args, **kwargs): 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 diff --git a/graphene/utils/subclass_with_meta.py b/graphene/utils/subclass_with_meta.py index 8900ad532..c4ee11d74 100644 --- a/graphene/utils/subclass_with_meta.py +++ b/graphene/utils/subclass_with_meta.py @@ -12,7 +12,7 @@ def __str__(cls): 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 @@ def __init_subclass__(cls, **meta_options): _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 @@ def __init_subclass__(cls, **meta_options): 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__"):