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

Fix up some typechecking #6150

Merged
merged 2 commits into from
Oct 2, 2019
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 .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*.tac
_trial_temp/
_trial_temp*/
/out

# stuff that is likely to exist when you run a server locally
/*.db
Expand Down
1 change: 1 addition & 0 deletions changelog.d/6150.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Expand type-checking on modules imported by synapse.config.
3 changes: 2 additions & 1 deletion synapse/api/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""Contains exceptions and error codes."""

import logging
from typing import Dict

from six import iteritems
from six.moves import http_client
Expand Down Expand Up @@ -111,7 +112,7 @@ class ProxiedRequestError(SynapseError):
def __init__(self, code, msg, errcode=Codes.UNKNOWN, additional_fields=None):
super(ProxiedRequestError, self).__init__(code, msg, errcode)
if additional_fields is None:
self._additional_fields = {}
self._additional_fields = {} # type: Dict
else:
self._additional_fields = dict(additional_fields)

Expand Down
5 changes: 4 additions & 1 deletion synapse/api/room_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Dict

import attr


Expand Down Expand Up @@ -102,4 +105,4 @@ class RoomVersions(object):
RoomVersions.V4,
RoomVersions.V5,
)
} # type: dict[str, RoomVersion]
} # type: Dict[str, RoomVersion]
4 changes: 3 additions & 1 deletion synapse/app/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,9 @@ def handle_sighup(*args, **kwargs):
refresh_certificate(hs)

# Start the tracer
synapse.logging.opentracing.init_tracer(hs.config)
synapse.logging.opentracing.init_tracer( # type: ignore[attr-defined] # noqa
hs.config
)

# It is now safe to start your Synapse.
hs.start_listening(listeners)
Expand Down
5 changes: 3 additions & 2 deletions synapse/config/appservice.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import logging
from typing import Dict

from six import string_types
from six.moves.urllib import parse as urlparse
Expand Down Expand Up @@ -56,8 +57,8 @@ def load_appservices(hostname, config_files):
return []

# Dicts of value -> filename
seen_as_tokens = {}
seen_ids = {}
seen_as_tokens = {} # type: Dict[str, str]
seen_ids = {} # type: Dict[str, str]

appservices = []

Expand Down
4 changes: 2 additions & 2 deletions synapse/config/consent_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@


class ConsentConfig(Config):
def __init__(self):
super(ConsentConfig, self).__init__()
def __init__(self, *args):
super(ConsentConfig, self).__init__(*args)

self.user_consent_version = None
self.user_consent_template_dir = None
Expand Down
4 changes: 3 additions & 1 deletion synapse/config/password_auth_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Any, List

from synapse.util.module_loader import load_module

from ._base import Config
Expand All @@ -22,7 +24,7 @@

class PasswordAuthProviderConfig(Config):
def read_config(self, config, **kwargs):
self.password_providers = []
self.password_providers = [] # type: List[Any]
providers = []

# We want to be backwards compatible with the old `ldap_config`
Expand Down
5 changes: 3 additions & 2 deletions synapse/config/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import os
from collections import namedtuple
from typing import Dict, List

from synapse.python_dependencies import DependencyException, check_requirements
from synapse.util.module_loader import load_module
Expand Down Expand Up @@ -61,7 +62,7 @@ def parse_thumbnail_requirements(thumbnail_sizes):
Dictionary mapping from media type string to list of
ThumbnailRequirement tuples.
"""
requirements = {}
requirements = {} # type: Dict[str, List]
for size in thumbnail_sizes:
width = size["width"]
height = size["height"]
Expand Down Expand Up @@ -130,7 +131,7 @@ def read_config(self, config, **kwargs):
#
# We don't create the storage providers here as not all workers need
# them to be started.
self.media_storage_providers = []
self.media_storage_providers = [] # type: List[tuple]

for provider_config in storage_providers:
# We special case the module "file_system" so as not to need to
Expand Down
10 changes: 7 additions & 3 deletions synapse/config/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import os.path
import re
from textwrap import indent
from typing import List

import attr
import yaml
Expand Down Expand Up @@ -243,7 +244,7 @@ def read_config(self, config, **kwargs):
# events with profile information that differ from the target's global profile.
self.allow_per_room_profiles = config.get("allow_per_room_profiles", True)

self.listeners = []
self.listeners = [] # type: List[dict]
for listener in config.get("listeners", []):
if not isinstance(listener.get("port", None), int):
raise ConfigError(
Expand Down Expand Up @@ -287,7 +288,10 @@ class LimitRemoteRoomsConfig(object):
validator=attr.validators.instance_of(bool), default=False
)
complexity = attr.ib(
validator=attr.validators.instance_of((int, float)), default=1.0
validator=attr.validators.instance_of(
(float, int) # type: ignore[arg-type] # noqa
),
default=1.0,
)
complexity_error = attr.ib(
validator=attr.validators.instance_of(str),
Expand Down Expand Up @@ -366,7 +370,7 @@ class LimitRemoteRoomsConfig(object):
"cleanup_extremities_with_dummy_events", True
)

def has_tls_listener(self):
def has_tls_listener(self) -> bool:
return any(l["tls"] for l in self.listeners)

def generate_config_section(
Expand Down
4 changes: 2 additions & 2 deletions synapse/config/server_notices_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ class ServerNoticesConfig(Config):
None if server notices are not enabled.
"""

def __init__(self):
super(ServerNoticesConfig, self).__init__()
def __init__(self, *args):
super(ServerNoticesConfig, self).__init__(*args)
self.server_notices_mxid = None
self.server_notices_mxid_display_name = None
self.server_notices_mxid_avatar_url = None
Expand Down
9 changes: 5 additions & 4 deletions synapse/logging/opentracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ def set_fates(clotho, lachesis, atropos, father="Zues", mother="Themis"):
import logging
import re
from functools import wraps
from typing import Dict

from canonicaljson import json

Expand Down Expand Up @@ -547,7 +548,7 @@ def inject_active_span_twisted_headers(headers, destination, check_destination=T
return

span = opentracing.tracer.active_span
carrier = {}
carrier = {} # type: Dict[str, str]
opentracing.tracer.inject(span, opentracing.Format.HTTP_HEADERS, carrier)

for key, value in carrier.items():
Expand Down Expand Up @@ -584,7 +585,7 @@ def inject_active_span_byte_dict(headers, destination, check_destination=True):

span = opentracing.tracer.active_span

carrier = {}
carrier = {} # type: Dict[str, str]
opentracing.tracer.inject(span, opentracing.Format.HTTP_HEADERS, carrier)

for key, value in carrier.items():
Expand Down Expand Up @@ -639,7 +640,7 @@ def get_active_span_text_map(destination=None):
if destination and not whitelisted_homeserver(destination):
return {}

carrier = {}
carrier = {} # type: Dict[str, str]
opentracing.tracer.inject(
opentracing.tracer.active_span, opentracing.Format.TEXT_MAP, carrier
)
Expand All @@ -653,7 +654,7 @@ def active_span_context_as_string():
Returns:
The active span context encoded as a string.
"""
carrier = {}
carrier = {} # type: Dict[str, str]
if opentracing:
opentracing.tracer.inject(
opentracing.tracer.active_span, opentracing.Format.TEXT_MAP, carrier
Expand Down
20 changes: 16 additions & 4 deletions synapse/logging/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,11 @@ def wrapped(*args, **kwargs):
logger = logging.getLogger(name)
level = logging.DEBUG

s = inspect.currentframe().f_back
frame = inspect.currentframe()
if frame is None:
raise Exception("Can't get current frame!")

s = frame.f_back

to_print = [
"\t%s:%s %s. Args: args=%s, kwargs=%s"
Expand All @@ -144,7 +148,7 @@ def wrapped(*args, **kwargs):
pathname=pathname,
lineno=lineno,
msg=msg,
args=None,
args=tuple(),
exc_info=None,
)

Expand All @@ -157,7 +161,12 @@ def wrapped(*args, **kwargs):


def get_previous_frames():
s = inspect.currentframe().f_back.f_back

frame = inspect.currentframe()
if frame is None:
raise Exception("Can't get current frame!")

s = frame.f_back.f_back
to_return = []
while s:
if s.f_globals["__name__"].startswith("synapse"):
Expand All @@ -174,7 +183,10 @@ def get_previous_frames():


def get_previous_frame(ignore=[]):
s = inspect.currentframe().f_back.f_back
frame = inspect.currentframe()
if frame is None:
raise Exception("Can't get current frame!")
s = frame.f_back.f_back

while s:
if s.f_globals["__name__"].startswith("synapse"):
Expand Down
4 changes: 2 additions & 2 deletions synapse/metrics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def __init__(self, name, desc, labels, sub_metrics):
)

# Counts number of in flight blocks for a given set of label values
self._registrations = {}
self._registrations = {} # type: Dict

# Protects access to _registrations
self._lock = threading.Lock()
Expand Down Expand Up @@ -226,7 +226,7 @@ def collect(self):
# Fetch the data -- this must be synchronous!
data = self.data_collector()

buckets = {}
buckets = {} # type: Dict[float, int]

res = []
for x in data.keys():
Expand Down
4 changes: 2 additions & 2 deletions synapse/metrics/_exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@
try:
from prometheus_client.samples import Sample
except ImportError:
Sample = namedtuple(
Sample = namedtuple( # type: ignore[no-redef] # noqa
"Sample", ["name", "labels", "value", "timestamp", "exemplar"]
) # type: ignore
)


CONTENT_TYPE_LATEST = str("text/plain; version=0.0.4; charset=utf-8")
Expand Down
17 changes: 13 additions & 4 deletions synapse/python_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# limitations under the License.

import logging
from typing import Set
from typing import List, Set

from pkg_resources import (
DistributionNotFound,
Expand Down Expand Up @@ -73,6 +73,7 @@
"netaddr>=0.7.18",
"Jinja2>=2.9",
"bleach>=1.4.3",
"typing-extensions>=3.7.4",
]

CONDITIONAL_REQUIREMENTS = {
Expand Down Expand Up @@ -144,7 +145,11 @@ def check_requirements(for_feature=None):
deps_needed.append(dependency)
errors.append(
"Needed %s, got %s==%s"
% (dependency, e.dist.project_name, e.dist.version)
% (
dependency,
e.dist.project_name, # type: ignore[attr-defined] # noqa
e.dist.version, # type: ignore[attr-defined] # noqa
)
)
except DistributionNotFound:
deps_needed.append(dependency)
Expand All @@ -159,7 +164,7 @@ def check_requirements(for_feature=None):
if not for_feature:
# Check the optional dependencies are up to date. We allow them to not be
# installed.
OPTS = sum(CONDITIONAL_REQUIREMENTS.values(), [])
OPTS = sum(CONDITIONAL_REQUIREMENTS.values(), []) # type: List[str]

for dependency in OPTS:
try:
Expand All @@ -168,7 +173,11 @@ def check_requirements(for_feature=None):
deps_needed.append(dependency)
errors.append(
"Needed optional %s, got %s==%s"
% (dependency, e.dist.project_name, e.dist.version)
% (
dependency,
e.dist.project_name, # type: ignore[attr-defined] # noqa
e.dist.version, # type: ignore[attr-defined] # noqa
)
)
except DistributionNotFound:
# If it's not found, we don't care
Expand Down
3 changes: 2 additions & 1 deletion synapse/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ class StreamToken(
)
):
_SEPARATOR = "_"
START = None # type: StreamToken

@classmethod
def from_string(cls, string):
Expand Down Expand Up @@ -402,7 +403,7 @@ class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
followed by the "stream_ordering" id of the event it comes after.
"""

__slots__ = []
__slots__ = [] # type: list

@classmethod
def parse(cls, string):
Expand Down
Loading