Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor for f strings. #984

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions UPGRADE-v2.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/relay/nodes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ Example of a custom node:

@staticmethod
def to_global_id(type, id):
return '{}:{}'.format(type, id)
return f'{type}:{id}'
changeling marked this conversation as resolved.
Show resolved Hide resolved

@staticmethod
def get_node_from_global_id(info, global_id, only_type=None):
Expand Down
4 changes: 2 additions & 2 deletions docs/types/objecttypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion examples/complex_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
54 changes: 25 additions & 29 deletions graphene/pyutils/signature.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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):
Expand All @@ -195,7 +195,7 @@ def __str__(self):
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")
Expand Down Expand Up @@ -249,7 +249,7 @@ def __init__(

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
Expand All @@ -263,7 +263,7 @@ def __init__(
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

Expand Down Expand Up @@ -325,14 +325,14 @@ def __str__(self):
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
Expand All @@ -342,10 +342,10 @@ def __str__(self):
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):
Expand Down Expand Up @@ -442,7 +442,7 @@ def kwargs(self):
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):
Expand Down Expand Up @@ -501,8 +501,7 @@ def __init__(
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
Expand All @@ -513,7 +512,7 @@ def __init__(
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:
Expand All @@ -527,7 +526,7 @@ def from_function(cls, func):
"""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

Expand Down Expand Up @@ -631,7 +630,7 @@ def replace(self, parameters=_void, return_annotation=_void):
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):
Expand Down Expand Up @@ -708,10 +707,9 @@ def _bind(self, args, kwargs, partial=False):
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
Expand All @@ -726,8 +724,7 @@ def _bind(self, args, kwargs, partial=False):
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
Expand All @@ -752,8 +749,7 @@ def _bind(self, args, kwargs, partial=False):

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
Expand All @@ -767,8 +763,8 @@ def _bind(self, args, kwargs, partial=False):
# 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:
Expand All @@ -790,7 +786,7 @@ def _bind(self, args, kwargs, partial=False):
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:
Expand Down Expand Up @@ -841,10 +837,10 @@ def __str__(self):

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
26 changes: 11 additions & 15 deletions graphene/relay/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,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
Expand All @@ -71,11 +69,9 @@ class EdgeBase(object):
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:
Expand Down Expand Up @@ -132,9 +128,9 @@ def type(self):
"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
Expand All @@ -143,9 +139,9 @@ def resolve_connection(cls, connection_type, args, resolved):
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,
Expand Down
12 changes: 6 additions & 6 deletions graphene/relay/mutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def __init_subclass_with_meta__(
input_fields = {}

cls.Input = type(
"{}Input".format(base_name),
f"{base_name}Input",
bases,
OrderedDict(
input_fields, client_mutation_id=String(name="clientMutationId")
Expand All @@ -42,12 +42,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
Expand All @@ -61,8 +61,8 @@ 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
Expand Down
6 changes: 3 additions & 3 deletions graphene/relay/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@ def get_node_from_global_id(cls, info, global_id, only_type=None):
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:
Expand Down
9 changes: 4 additions & 5 deletions graphene/types/argument.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 2 additions & 2 deletions graphene/types/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)}>"
changeling marked this conversation as resolved.
Show resolved Hide resolved


class BaseType(SubclassWithMeta):
Expand Down
Loading