Refactor string .format() to f-string syntax. Minor corrections. Blackened project.

Rebased to trigger ci.

Blackened project, due to Travis failures.

f-string formatting where applicable.
Minor corrections to language.

Corrected typo, missing parens.

Update test_structures.py to match updated phrasing.

Bowing to the wisdom of black.

As per black, adjusted line length in types/argument.py (line 67).

One  more kick in the pants by black.

More f-strings.

More blackening.
This commit is contained in:
changeling 2019-06-01 18:52:15 -05:00
parent 67c4310c78
commit a432239d1f
29 changed files with 125 additions and 153 deletions

View File

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

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

@ -26,7 +26,7 @@ This example model defines a Person, with a first and a last name:
full_name = graphene.String()
def resolve_full_name(root, info):
return '{} {}'.format(root.first_name, root.last_name)
return f'{root.first_name} {root.last_name}'
**first\_name** and **last\_name** are fields of the ObjectType. Each
field is specified as a class attribute, and each attribute maps to a
@ -173,7 +173,7 @@ A field can use a custom resolver from outside the class:
import graphene
def resolve_full_name(person, info):
return '{} {}'.format(person.first_name, person.last_name)
return f'{person.first_name} {person.last_name}'
class Person(graphene.ObjectType):
first_name = graphene.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

@ -54,7 +54,7 @@ def signature(obj):
"""Get a signature object for the passed callable."""
if not callable(obj):
raise TypeError("{!r} is not a callable object".format(obj))
raise TypeError(f"{repr(obj)} is not a callable object")
if isinstance(obj, types.MethodType):
sig = signature(obj.__func__)
@ -101,7 +101,7 @@ def signature(obj):
try:
ba = sig.bind_partial(*partial_args, **partial_keywords)
except TypeError as ex:
msg = "partial object {!r} has incorrect arguments".format(obj)
msg = f"partial object {repr(obj)} has incorrect arguments"
raise ValueError(msg)
for arg_name, arg_value in ba.arguments.items():
@ -171,10 +171,10 @@ def signature(obj):
if isinstance(obj, types.BuiltinFunctionType):
# Raise a nicer error message for builtins
msg = "no signature found for builtin function {!r}".format(obj)
msg = f"no signature found for builtin function {repr(obj)}"
raise ValueError(msg)
raise ValueError("callable {!r} is not supported by signature".format(obj))
raise ValueError(f"callable {repr(obj)} is not supported by signature")
class _void(object):
@ -195,7 +195,7 @@ class _ParameterKind(int):
return self._name
def __repr__(self):
return "<_ParameterKind: {!r}>".format(self._name)
return f"<_ParameterKind: {repr(self._name)}>"
_POSITIONAL_ONLY = _ParameterKind(0, name="POSITIONAL_ONLY")
@ -249,7 +249,7 @@ class Parameter(object):
if default is not _empty:
if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
msg = "{} parameters cannot have default values".format(kind)
msg = f"{kind} parameters cannot have default values"
raise ValueError(msg)
self._default = default
self._annotation = annotation
@ -263,7 +263,7 @@ class Parameter(object):
else:
name = str(name)
if kind != _POSITIONAL_ONLY and not re.match(r"[a-z_]\w*$", name, re.I):
msg = "{!r} is not a valid parameter name".format(name)
msg = f"{repr(name)} is not a valid parameter name"
raise ValueError(msg)
self._name = name
@ -325,14 +325,14 @@ class Parameter(object):
if kind == _POSITIONAL_ONLY:
if formatted is None:
formatted = ""
formatted = "<{}>".format(formatted)
formatted = f"<{formatted}>"
# Add annotation and default value
if self._annotation is not _empty:
formatted = "{}:{}".format(formatted, formatannotation(self._annotation))
formatted = f"{formatted}:{formatannotation(self._annotation)}"
if self._default is not _empty:
formatted = "{}={}".format(formatted, repr(self._default))
formatted = f"{formatted}={repr(self._default)}"
if kind == _VAR_POSITIONAL:
formatted = "*" + formatted
@ -342,10 +342,10 @@ class Parameter(object):
return formatted
def __repr__(self):
return "<{} at {:#x} {!r}>".format(self.__class__.__name__, id(self), self.name)
return f"<{self.__class__.__name__} at {id(self):#x} {repr(self.name)}>"
def __hash__(self):
msg = "unhashable type: '{}'".format(self.__class__.__name__)
msg = f"unhashable type: '{self.__class__.__name__}'"
raise TypeError(msg)
def __eq__(self, other):
@ -442,7 +442,7 @@ class BoundArguments(object):
return kwargs
def __hash__(self):
msg = "unhashable type: '{}'".format(self.__class__.__name__)
msg = f"unhashable type: '{self.__class__.__name__}'"
raise TypeError(msg)
def __eq__(self, other):
@ -501,8 +501,7 @@ class Signature(object):
for idx, param in enumerate(parameters):
kind = param.kind
if kind < top_kind:
msg = "wrong parameter order: {0} before {1}"
msg = msg.format(top_kind, param.kind)
msg = f"wrong parameter order: {top_kind} before {param.kind}"
raise ValueError(msg)
else:
top_kind = kind
@ -513,7 +512,7 @@ class Signature(object):
param = param.replace(name=name)
if name in params:
msg = "duplicate parameter name: {!r}".format(name)
msg = f"duplicate parameter name: {repr(name)}"
raise ValueError(msg)
params[name] = param
else:
@ -527,7 +526,7 @@ class Signature(object):
"""Constructs Signature for the given python function"""
if not isinstance(func, types.FunctionType):
raise TypeError("{!r} is not a Python function".format(func))
raise TypeError(f"{repr(func)} is not a Python function")
Parameter = cls._parameter_cls
@ -631,7 +630,7 @@ class Signature(object):
return type(self)(parameters, return_annotation=return_annotation)
def __hash__(self):
msg = "unhashable type: '{}'".format(self.__class__.__name__)
msg = f"unhashable type: '{self.__class__.__name__}'"
raise TypeError(msg)
def __eq__(self, other):
@ -708,10 +707,9 @@ class Signature(object):
elif param.name in kwargs:
if param.kind == _POSITIONAL_ONLY:
msg = (
"{arg!r} parameter is positional only, "
f"{repr(param.name)} parameter is positional only, "
"but was passed as a keyword"
)
msg = msg.format(arg=param.name)
raise TypeError(msg)
parameters_ex = (param,)
break
@ -726,8 +724,7 @@ class Signature(object):
parameters_ex = (param,)
break
else:
msg = "{arg!r} parameter lacking default value"
msg = msg.format(arg=param.name)
msg = f"{repr(param.name)} parameter lacking default value"
raise TypeError(msg)
else:
# We have a positional argument to process
@ -752,8 +749,7 @@ class Signature(object):
if param.name in kwargs:
raise TypeError(
"multiple values for argument "
"{arg!r}".format(arg=param.name)
f"multiple values for argument {repr(param.name)}"
)
arguments[param.name] = arg_val
@ -767,8 +763,8 @@ class Signature(object):
# Signature object (but let's have this check here
# to ensure correct behaviour just in case)
raise TypeError(
"{arg!r} parameter is positional only, "
"but was passed as a keyword".format(arg=param.name)
f"{repr(param.name)} parameter is positional only, "
"but was passed as a keyword"
)
if param.kind == _VAR_KEYWORD:
@ -790,7 +786,7 @@ class Signature(object):
and param.default is _empty
):
raise TypeError(
"{arg!r} parameter lacking default value".format(arg=param_name)
f"{repr(param_name)} parameter lacking default value"
)
else:
@ -841,10 +837,10 @@ class Signature(object):
result.append(formatted)
rendered = "({})".format(", ".join(result))
rendered = f"({', '.join(result)})"
if self.return_annotation is not _empty:
anno = formatannotation(self.return_annotation)
rendered += " -> {}".format(anno)
rendered += f" -> {anno}"
return rendered

View File

@ -52,16 +52,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
@ -71,11 +69,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:
@ -132,9 +128,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 have to be a subclass of Connection. Received "{}".'
).format(self.__class__.__name__, connection_type)
assert issubclass(
connection_type, Connection
), f'{self.__class__.__name__} type have to be a subclass of Connection. Received "{connection_type}".'
return type
@classmethod
@ -143,9 +139,9 @@ class IterableConnectionField(Field):
return resolved
assert isinstance(resolved, Iterable), (
"Resolved value from the connection field have to be iterable or instance of {}. "
'Received "{}"'
).format(connection_type, resolved)
f"Resolved value from the connection field has to be iterable or instance of {connection_type}. "
f'Received "{resolved}"'
)
connection = connection_from_list(
resolved,
args,

View File

@ -28,7 +28,7 @@ class ClientIDMutation(Mutation):
input_fields = {}
cls.Input = type(
"{}Input".format(base_name),
f"{base_name}Input",
bases,
OrderedDict(
input_fields, client_mutation_id=String(name="clientMutationId")
@ -42,12 +42,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
@ -61,8 +61,8 @@ 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

@ -98,9 +98,9 @@ class Node(AbstractNode):
return None
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:

View File

@ -64,18 +64,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, but received {type(arg).__name__}. "
f"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(object):
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,7 +21,7 @@ class Date(Scalar):
date = date.date()
assert isinstance(
date, datetime.date
), 'Received not compatible date "{}"'.format(repr(date))
), f'Received incompatible date "{repr(date)}"'
return date.isoformat()
@classmethod
@ -51,7 +51,7 @@ class DateTime(Scalar):
def serialize(dt):
assert isinstance(
dt, (datetime.datetime, datetime.date)
), 'Received not compatible datetime "{}"'.format(repr(dt))
), f'Received incompatible datetime "{repr(dt)}"'
return dt.isoformat()
@classmethod
@ -81,7 +81,7 @@ class Time(Scalar):
def serialize(time):
assert isinstance(
time, datetime.time
), 'Received not compatible time "{}"'.format(repr(time))
), f'Received incompatible time "{repr(time)}"'
return time.isoformat()
@classmethod

View File

@ -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 incompatible Decimal "{repr(dec)}"'
return str(dec)
@classmethod

View File

@ -31,18 +31,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

@ -48,11 +48,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

@ -31,7 +31,7 @@ class ObjectType(BaseType):
possible_types=(),
default_resolver=None,
_meta=None,
**options
**options,
):
if not _meta:
_meta = ObjectTypeOptions(cls)
@ -39,18 +39,18 @@ class ObjectType(BaseType):
fields = OrderedDict()
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)
@ -102,7 +102,5 @@ 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 for {self.__class__.__name__}"
)

View File

@ -20,9 +20,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."
class Schema(GraphQLSchema):
@ -55,9 +55,7 @@ class Schema(GraphQLSchema):
assert all(
isinstance(d, GraphQLDirective) for d in directives
), "Schema directives must be List[GraphQLDirective] if provided but got: {}.".format(
directives
)
), f"Schema directives must be List[GraphQLDirective] if provided but got: {directives}."
self._directives = directives
self.build_typemap()
@ -79,7 +77,7 @@ class Schema(GraphQLSchema):
"""
_type = super(Schema, self).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
@ -91,12 +89,10 @@ class Schema(GraphQLSchema):
return _type
if is_graphene_type(_type):
graphql_type = self.get_type(_type._meta.name)
assert graphql_type, "Type {} not found in this schema.".format(
_type._meta.name
)
assert graphql_type, f"Type {_type._meta.name} not found in this schema."
assert graphql_type.graphene_type == _type
return graphql_type
raise Exception("{} is not a valid GraphQL type.".format(_type))
raise Exception(f"{_type} is not a valid GraphQL type.")
def execute(self, *args, **kwargs):
return graphql(self, *args, **kwargs)

View File

@ -14,9 +14,7 @@ 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} can not have a mounted {of_type_name}() as inner type. Try {cls_name}({of_type_name})."
)
self._of_type = of_type
@ -42,7 +40,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 (
@ -67,12 +65,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

@ -169,9 +169,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 len(result.errors) == 1

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

@ -448,15 +448,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

@ -19,7 +19,7 @@ def test_list_with_unmounted_type():
assert (
str(exc_info.value)
== "List could not have a mounted String() as inner type. Try with List(String)."
== "List can not have a mounted String() as inner type. Try List(String)."
)
@ -97,7 +97,7 @@ def test_nonnull_with_unmounted_type():
assert (
str(exc_info.value)
== "NonNull could not have a mounted String() as inner type. Try with NonNull(String)."
== "NonNull can not have a mounted String() as inner type. Try NonNull(String)."
)

View File

@ -32,7 +32,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

@ -60,10 +60,10 @@ def resolve_type(resolve_type_func, map, type_name, root, info):
if inspect.isclass(_type) and issubclass(_type, ObjectType):
graphql_type = map.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 associated graphene type {graphql_type.graphene_type}."
return graphql_type
return _type
@ -94,9 +94,9 @@ class TypeMap(GraphQLTypeMap):
if type._meta.name in map:
_type = map[type._meta.name]
if isinstance(_type, GrapheneGraphQLType):
assert _type.graphene_type == type, (
"Found different types with the same name in the schema: {}, {}."
).format(_type.graphene_type, type)
assert (
_type.graphene_type == type
), f"Found different types with the same name in the schema: {_type.graphene_type}, {type}."
return map
if issubclass(type, ObjectType):
@ -112,7 +112,7 @@ class TypeMap(GraphQLTypeMap):
elif issubclass(type, Union):
internal_type = self.construct_union(map, type)
else:
raise Exception("Expected Graphene type, but received: {}.".format(type))
raise Exception(f"Expected Graphene type, but received: {type}.")
return GraphQLTypeMap.reducer(map, internal_type)
@ -173,9 +173,9 @@ class TypeMap(GraphQLTypeMap):
if type._meta.name in map:
_type = map[type._meta.name]
if isinstance(_type, GrapheneGraphQLType):
assert _type.graphene_type == type, (
"Found different types with the same name in the schema: {}, {}."
).format(_type.graphene_type, type)
assert (
_type.graphene_type == type
), f"Found different types with the same name in the schema: {_type.graphene_type}, {type}."
return _type
def interfaces():
@ -207,9 +207,9 @@ class TypeMap(GraphQLTypeMap):
if type._meta.name in map:
_type = map[type._meta.name]
if isinstance(_type, GrapheneInterfaceType):
assert _type.graphene_type == type, (
"Found different types with the same name in the schema: {}, {}."
).format(_type.graphene_type, type)
assert (
_type.graphene_type == type
), f"Found different types with the same name in the schema: {_type.graphene_type}, {type}."
return _type
_resolve_type = None
@ -309,7 +309,7 @@ class TypeMap(GraphQLTypeMap):
def get_resolver_for_type(self, type, name, default_value):
if not issubclass(type, ObjectType):
return
resolver = getattr(type, "resolve_{}".format(name), None)
resolver = getattr(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
@ -317,7 +317,7 @@ class TypeMap(GraphQLTypeMap):
for interface in 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

View File

@ -25,7 +25,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

@ -25,7 +25,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

@ -14,9 +14,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

@ -13,7 +13,7 @@ class SubclassWithMeta_Meta(InitSubclassMeta):
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):
@ -31,9 +31,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)
@ -42,8 +40,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.keys()))
f"Received: abstract, {', '.join(options.keys())}"
)
else:
super_class = super(cls, cls)
if hasattr(super_class, "__init_subclass_with_meta__"):