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() id = ID()
def resolve_id(self, info): def resolve_id(self, info):
return "{type}_{id}".format( return f"{self.__class__.__name__}_{self.id}"
type=self.__class__.__name__,
id=self.id
)
``` ```
### UUID Scalar ### UUID Scalar

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

@ -26,7 +26,7 @@ This example model defines a Person, with a first and a last name:
full_name = graphene.String() full_name = graphene.String()
def resolve_full_name(root, info): 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 **first\_name** and **last\_name** are fields of the ObjectType. Each
field is specified as a class attribute, and each attribute maps to a 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 import graphene
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(graphene.ObjectType): class Person(graphene.ObjectType):
first_name = graphene.String() first_name = graphene.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

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

View File

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

View File

@ -28,7 +28,7 @@ class ClientIDMutation(Mutation):
input_fields = {} input_fields = {}
cls.Input = type( cls.Input = type(
"{}Input".format(base_name), f"{base_name}Input",
bases, bases,
OrderedDict( OrderedDict(
input_fields, client_mutation_id=String(name="clientMutationId") 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) 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
@ -61,8 +61,8 @@ 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( (
repr(payload) f"Cannot set client_mutation_id in the payload object {repr(payload)}"
) )
) )
return payload return payload

View File

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

View File

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

View File

@ -16,9 +16,7 @@ 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(dec, _Decimal), f'Received incompatible Decimal "{repr(dec)}"'
repr(dec)
)
return str(dec) return str(dec)
@classmethod @classmethod

View File

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

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

@ -31,7 +31,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)
@ -39,18 +39,18 @@ class ObjectType(BaseType):
fields = OrderedDict() fields = OrderedDict()
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)
@ -102,7 +102,5 @@ 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 for {self.__class__.__name__}"
list(kwargs)[0], self.__class__.__name__
)
) )

View File

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

View File

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

@ -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(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 len(result.errors) == 1 assert len(result.errors) == 1

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

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

@ -19,7 +19,7 @@ def test_list_with_unmounted_type():
assert ( assert (
str(exc_info.value) 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 ( assert (
str(exc_info.value) 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 @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

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

View File

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

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

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

@ -13,7 +13,7 @@ class SubclassWithMeta_Meta(InitSubclassMeta):
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):
@ -31,9 +31,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)
@ -42,8 +40,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.keys())}"
).format(option_keys=", ".join(options.keys())) )
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__"):