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

Updated all str.format(…) to f-strings #1158

Merged
merged 5 commits into from
Mar 15, 2020
Merged
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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ repos:
hooks:
- id: pyupgrade
- repo: https://github.com/ambv/black
rev: 19.3b0
rev: 19.10b0
hooks:
- id: black
language_version: python3
Expand Down
5 changes: 1 addition & 4 deletions UPGRADE-v2.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 3 additions & 6 deletions docs/execution/middleware.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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


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}"

@staticmethod
def get_node_from_global_id(info, global_id, only_type=None):
Expand Down
2 changes: 1 addition & 1 deletion docs/types/objecttypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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()
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
26 changes: 11 additions & 15 deletions graphene/relay/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -141,9 +137,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 has to be a subclass of Connection. Received "{}".'
).format(self.__class__.__name__, connection_type)
assert issubclass(
connection_type, Connection
), f'{self.__class__.__name__} type has to be a subclass of Connection. Received "{connection_type}".'
return type

@classmethod
Expand All @@ -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,
Expand Down
12 changes: 5 additions & 7 deletions graphene/relay/mutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")),
)
Expand All @@ -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
Expand All @@ -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

Expand Down
22 changes: 8 additions & 14 deletions graphene/relay/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def __init__(self, node, type=False, **kwargs):
# interface
type or node,
id=ID(required=True, description="The ID of the object"),
**kwargs
**kwargs,
)

def get_resolver(self, parent_resolver):
Expand Down Expand Up @@ -93,33 +93,27 @@ 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)
)
raise Exception(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)
Expand Down
36 changes: 12 additions & 24 deletions graphene/relay/tests/test_connection_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,32 +134,28 @@ 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
)
await check(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
)
await check(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,
)
Expand All @@ -168,23 +164,21 @@ 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")),
"BCD",
f'first: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
)


@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")),
"BCD",
f'first: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
)


@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,
)
Expand All @@ -193,16 +187,14 @@ 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")),
"BCD",
f'last: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
)


@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")),
"BCD",
f'last: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD",
)


Expand All @@ -219,19 +211,15 @@ 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",
)


@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)}"',
"",
)

Expand Down
9 changes: 4 additions & 5 deletions graphene/types/argument.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,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, "
f"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
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)}>"


class BaseType(SubclassWithMeta):
Expand Down
Loading