Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Run pyupgrade for python 3.7 & 3.8. #16110

Merged
merged 4 commits into from
Aug 15, 2023
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
1 change: 1 addition & 0 deletions changelog.d/16110.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Run `pyupgrade` for Python 3.8+.
2 changes: 1 addition & 1 deletion contrib/cmdclient/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,7 +769,7 @@ def main(server_url, identity_server_url, username, token, config_path):
global CONFIG_JSON
CONFIG_JSON = config_path # bit cheeky, but just overwrite the global
try:
with open(config_path, "r") as config:
with open(config_path) as config:
syn_cmd.config = json.load(config)
try:
http_client.verbose = "on" == syn_cmd.config["verbose"]
Expand Down
2 changes: 1 addition & 1 deletion docker/configure_workers_and_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,7 +861,7 @@ def generate_worker_files(
# Then a worker config file
convert(
"/conf/worker.yaml.j2",
"/conf/workers/{name}.yaml".format(name=worker_name),
f"/conf/workers/{worker_name}.yaml",
**worker_config,
worker_log_config_filepath=log_config_filepath,
using_unix_sockets=using_unix_sockets,
Expand Down
2 changes: 1 addition & 1 deletion docker/start.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def generate_config_from_template(
with open(filename) as handle:
value = handle.read()
else:
log("Generating a random secret for {}".format(secret))
log(f"Generating a random secret for {secret}")
value = codecs.encode(os.urandom(32), "hex").decode()
with open(filename, "w") as handle:
handle.write(value)
Expand Down
2 changes: 1 addition & 1 deletion scripts-dev/build_debian_packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
projdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))


class Builder(object):
class Builder:
def __init__(
self,
redirect_stdout: bool = False,
Expand Down
2 changes: 1 addition & 1 deletion scripts-dev/check_schema_delta.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def main(force_colors: bool) -> None:
diffs: List[git.Diff] = repo.remote().refs.develop.commit.diff(None)

# Get the schema version of the local file to check against current schema on develop
with open("synapse/storage/schema/__init__.py", "r") as file:
with open("synapse/storage/schema/__init__.py") as file:
local_schema = file.read()
new_locals: Dict[str, Any] = {}
exec(local_schema, new_locals)
Expand Down
2 changes: 1 addition & 1 deletion scripts-dev/federation_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def main() -> None:


def read_args_from_config(args: argparse.Namespace) -> None:
with open(args.config, "r") as fh:
with open(args.config) as fh:
config = yaml.safe_load(fh)

if not args.server_name:
Expand Down
1 change: 0 additions & 1 deletion scripts-dev/release.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
2 changes: 1 addition & 1 deletion scripts-dev/sign_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def main() -> None:


def read_args_from_config(args: argparse.Namespace) -> None:
with open(args.config, "r") as fh:
with open(args.config) as fh:
config = yaml.safe_load(fh)
if not args.server_name:
args.server_name = config["server_name"]
Expand Down
8 changes: 6 additions & 2 deletions synapse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@
from synapse.util.stringutils import strtobool

# Check that we're not running on an unsupported Python version.
if sys.version_info < (3, 8):
#
# Note that we use an (unneeded) variable here so that pyupgrade doesn't nuke the
# if-statement completely.
py_version = sys.version_info
if py_version < (3, 8):
Comment on lines +29 to +32
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without this change pyupgrade assumes you don't need this code and just removes it. Hopefully my comment is clear enough?

print("Synapse requires Python 3.8 or above.")
sys.exit(1)

Expand Down Expand Up @@ -78,7 +82,7 @@ def _immutabledict_cb(d: immutabledict) -> Dict[str, Any]:
except ImportError:
pass

import synapse.util
import synapse.util # noqa: E402

__version__ = synapse.util.SYNAPSE_VERSION

Expand Down
6 changes: 3 additions & 3 deletions synapse/_scripts/synapse_port_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -1205,10 +1205,10 @@ def __init__(self, stdscr: "curses.window"):
self.total_processed = 0
self.total_remaining = 0

super(CursesProgress, self).__init__()
super().__init__()

def update(self, table: str, num_done: int) -> None:
super(CursesProgress, self).update(table, num_done)
super().update(table, num_done)

self.total_processed = 0
self.total_remaining = 0
Expand Down Expand Up @@ -1304,7 +1304,7 @@ class TerminalProgress(Progress):
"""Just prints progress to the terminal"""

def update(self, table: str, num_done: int) -> None:
super(TerminalProgress, self).update(table, num_done)
super().update(table, num_done)

data = self.tables[table]

Expand Down
2 changes: 1 addition & 1 deletion synapse/_scripts/update_synapse_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class MockHomeserver(HomeServer):
DATASTORE_CLASS = DataStore # type: ignore [assignment]

def __init__(self, config: HomeServerConfig):
super(MockHomeserver, self).__init__(
super().__init__(
hostname=config.server.server_name,
config=config,
reactor=reactor,
Expand Down
3 changes: 1 addition & 2 deletions synapse/api/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@
"""Contains constants from the specification."""

import enum

from typing_extensions import Final
from typing import Final

# the max size of a (canonical-json-encoded) event
MAX_PDU_SIZE = 65536
Expand Down
2 changes: 1 addition & 1 deletion synapse/handlers/presence.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
Any,
Callable,
Collection,
ContextManager,
Dict,
Generator,
Iterable,
Expand All @@ -43,7 +44,6 @@
)

from prometheus_client import Counter
from typing_extensions import ContextManager

import synapse.metrics
from synapse.api.constants import EduTypes, EventTypes, Membership, PresenceState
Expand Down
5 changes: 3 additions & 2 deletions synapse/handlers/sso.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@
Iterable,
List,
Mapping,
NoReturn,
Optional,
Set,
)
from urllib.parse import urlencode

import attr
from typing_extensions import NoReturn, Protocol
from typing_extensions import Protocol
clokep marked this conversation as resolved.
Show resolved Hide resolved

from twisted.web.iweb import IRequest
from twisted.web.server import Request
Expand Down Expand Up @@ -791,7 +792,7 @@ def is_allowed_mime_type(content_type: str) -> bool:

if code != 200:
raise Exception(
"GET request to download sso avatar image returned {}".format(code)
f"GET request to download sso avatar image returned {code}"
)

# upload name includes hash of the image file's content so that we can
Expand Down
12 changes: 9 additions & 3 deletions synapse/handlers/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,15 @@
# limitations under the License.
import logging
from collections import Counter
from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Tuple

from typing_extensions import Counter as CounterType
from typing import (
TYPE_CHECKING,
Any,
Counter as CounterType,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like we should be able to just use collections.Counter[str] in 3.9: https://docs.python.org/3/library/typing.html?highlight=typing%20protocol#typing.Counter

Dict,
Iterable,
Optional,
Tuple,
)

from synapse.api.constants import EventContentFields, EventTypes, Membership
from synapse.metrics import event_processing_positions
Expand Down
8 changes: 3 additions & 5 deletions synapse/handlers/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -1442,11 +1442,9 @@ async def generate_sync_result(

# Now we have our list of joined room IDs, exclude as configured and freeze
joined_room_ids = frozenset(
(
room_id
for room_id in mutable_joined_room_ids
if room_id not in mutable_rooms_to_exclude
)
room_id
for room_id in mutable_joined_room_ids
if room_id not in mutable_rooms_to_exclude
)

logger.debug(
Expand Down
3 changes: 1 addition & 2 deletions synapse/logging/_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@
from collections import deque
from ipaddress import IPv4Address, IPv6Address, ip_address
from math import floor
from typing import Callable, Optional
from typing import Callable, Deque, Optional

import attr
from typing_extensions import Deque
from zope.interface import implementer

from twisted.application.internet import ClientService
Expand Down
48 changes: 12 additions & 36 deletions synapse/module_api/callbacks/spamchecker_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,9 +426,7 @@ async def check_event_for_spam(
generally discouraged as it doesn't support internationalization.
"""
for callback in self._check_event_for_spam_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res = await delay_cancellation(callback(event))
if res is False or res == self.NOT_SPAM:
# This spam-checker accepts the event.
Expand Down Expand Up @@ -481,9 +479,7 @@ async def should_drop_federated_event(
True if the event should be silently dropped
"""
for callback in self._should_drop_federated_event_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res: Union[bool, str] = await delay_cancellation(callback(event))
if res:
return res
Expand All @@ -505,9 +501,7 @@ async def user_may_join_room(
NOT_SPAM if the operation is permitted, [Codes, Dict] otherwise.
"""
for callback in self._user_may_join_room_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res = await delay_cancellation(callback(user_id, room_id, is_invited))
# Normalize return values to `Codes` or `"NOT_SPAM"`.
if res is True or res is self.NOT_SPAM:
Expand Down Expand Up @@ -546,9 +540,7 @@ async def user_may_invite(
NOT_SPAM if the operation is permitted, Codes otherwise.
"""
for callback in self._user_may_invite_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res = await delay_cancellation(
callback(inviter_userid, invitee_userid, room_id)
)
Expand Down Expand Up @@ -593,9 +585,7 @@ async def user_may_send_3pid_invite(
NOT_SPAM if the operation is permitted, Codes otherwise.
"""
for callback in self._user_may_send_3pid_invite_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res = await delay_cancellation(
callback(inviter_userid, medium, address, room_id)
)
Expand Down Expand Up @@ -630,9 +620,7 @@ async def user_may_create_room(
userid: The ID of the user attempting to create a room
"""
for callback in self._user_may_create_room_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res = await delay_cancellation(callback(userid))
if res is True or res is self.NOT_SPAM:
continue
Expand Down Expand Up @@ -666,9 +654,7 @@ async def user_may_create_room_alias(

"""
for callback in self._user_may_create_room_alias_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res = await delay_cancellation(callback(userid, room_alias))
if res is True or res is self.NOT_SPAM:
continue
Expand Down Expand Up @@ -701,9 +687,7 @@ async def user_may_publish_room(
room_id: The ID of the room that would be published
"""
for callback in self._user_may_publish_room_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res = await delay_cancellation(callback(userid, room_id))
if res is True or res is self.NOT_SPAM:
continue
Expand Down Expand Up @@ -742,9 +726,7 @@ async def check_username_for_spam(self, user_profile: UserProfile) -> bool:
True if the user is spammy.
"""
for callback in self._check_username_for_spam_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
# Make a copy of the user profile object to ensure the spam checker cannot
# modify it.
res = await delay_cancellation(callback(user_profile.copy()))
Expand Down Expand Up @@ -776,9 +758,7 @@ async def check_registration_for_spam(
"""

for callback in self._check_registration_for_spam_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
behaviour = await delay_cancellation(
callback(email_threepid, username, request_info, auth_provider_id)
)
Expand Down Expand Up @@ -820,9 +800,7 @@ async def check_media_file_for_spam(
"""

for callback in self._check_media_file_for_spam_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res = await delay_cancellation(callback(file_wrapper, file_info))
# Normalize return values to `Codes` or `"NOT_SPAM"`.
if res is False or res is self.NOT_SPAM:
Expand Down Expand Up @@ -869,9 +847,7 @@ async def check_login_for_spam(
"""

for callback in self._check_login_for_spam_callbacks:
with Measure(
self.clock, "{}.{}".format(callback.__module__, callback.__qualname__)
):
with Measure(self.clock, f"{callback.__module__}.{callback.__qualname__}"):
res = await delay_cancellation(
callback(
user_id,
Expand Down
2 changes: 1 addition & 1 deletion synapse/replication/tcp/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
TYPE_CHECKING,
Any,
Awaitable,
Deque,
Dict,
Iterable,
Iterator,
Expand All @@ -29,7 +30,6 @@
)

from prometheus_client import Counter
from typing_extensions import Deque

from twisted.internet.protocol import ReconnectingClientFactory

Expand Down
3 changes: 1 addition & 2 deletions synapse/storage/databases/main/filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Optional, Tuple, Union, cast
from typing import TYPE_CHECKING, Optional, Tuple, Union, cast

from canonicaljson import encode_canonical_json
from typing_extensions import TYPE_CHECKING

from synapse.api.errors import Codes, StoreError, SynapseError
from synapse.storage._base import SQLBaseStore, db_to_json
Expand Down
2 changes: 1 addition & 1 deletion synapse/storage/databases/main/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ async def store_server_keys_json(
# invalidate takes a tuple corresponding to the params of
# _get_server_keys_json. _get_server_keys_json only takes one
# param, which is itself the 2-tuple (server_name, key_id).
self._get_server_keys_json.invalidate((((server_name, key_id),)))
self._get_server_keys_json.invalidate(((server_name, key_id),))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is safe: before we have invalidate( (t1) ) where t1 = (t2,). We are removing the inner brackets around t1.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we have 4 sets of parens, if you expand it out you have:

  1. Function call
  2. Grouping (unneeded)
  3. Tuple
  4. Tuple
invalidate( #function call
    ( # grouping
        ( # tuple
            ( # tuple
                server_name, key_id
            ),
        )
    )
)


@cached()
def _get_server_keys_json(
Expand Down
Loading
Loading