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

Add more type hints to synapse.util. #11321

Merged
merged 2 commits into from
Nov 12, 2021
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/11321.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add type hints to `synapse.util`.
6 changes: 3 additions & 3 deletions synapse/http/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def return_json_error(f: failure.Failure, request: SynapseRequest) -> None:
"Failed handle request via %r: %r",
request.request_metrics.name,
request,
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
)

# Only respond with an error response if we haven't already started writing,
Expand Down Expand Up @@ -150,7 +150,7 @@ def return_html_error(
logger.error(
"Failed handle request %r",
request,
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
)
else:
code = HTTPStatus.INTERNAL_SERVER_ERROR
Expand All @@ -159,7 +159,7 @@ def return_html_error(
logger.error(
"Failed handle request %r",
request,
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
)

if isinstance(error_template, str):
Expand Down
32 changes: 20 additions & 12 deletions synapse/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import logging
import re
import typing
from typing import Any, Callable, Dict, Generator, Pattern
from typing import Any, Callable, Dict, Generator, Optional, Pattern

import attr
from frozendict import frozendict
Expand Down Expand Up @@ -110,7 +110,9 @@ def time_msec(self) -> int:
"""Returns the current system time in milliseconds since epoch."""
return int(self.time() * 1000)

def looping_call(self, f: Callable, msec: float, *args, **kwargs) -> LoopingCall:
def looping_call(
self, f: Callable, msec: float, *args: Any, **kwargs: Any
) -> LoopingCall:
"""Call a function repeatedly.

Waits `msec` initially before calling `f` for the first time.
Expand All @@ -130,20 +132,22 @@ def looping_call(self, f: Callable, msec: float, *args, **kwargs) -> LoopingCall
d.addErrback(log_failure, "Looping call died", consumeErrors=False)
return call

def call_later(self, delay, callback, *args, **kwargs) -> IDelayedCall:
def call_later(
self, delay: float, callback: Callable, *args: Any, **kwargs: Any
) -> IDelayedCall:
"""Call something later

Note that the function will be called with no logcontext, so if it is anything
other than trivial, you probably want to wrap it in run_as_background_process.

Args:
delay(float): How long to wait in seconds.
callback(function): Function to call
delay: How long to wait in seconds.
callback: Function to call
*args: Postional arguments to pass to function.
**kwargs: Key arguments to pass to function.
"""

def wrapped_callback(*args, **kwargs):
def wrapped_callback(*args: Any, **kwargs: Any) -> None:
with context.PreserveLoggingContext():
callback(*args, **kwargs)

Expand All @@ -158,25 +162,29 @@ def cancel_call_later(self, timer: IDelayedCall, ignore_errs: bool = False) -> N
raise


def log_failure(failure, msg, consumeErrors=True):
def log_failure(
failure: Failure, msg: str, consumeErrors: bool = True
) -> Optional[Failure]:
"""Creates a function suitable for passing to `Deferred.addErrback` that
logs any failures that occur.

Args:
msg (str): Message to log
consumeErrors (bool): If true consumes the failure, otherwise passes
on down the callback chain
failure: The Failure to log
msg: Message to log
consumeErrors: If true consumes the failure, otherwise passes on down
the callback chain

Returns:
func(Failure)
The Failure if consumeErrors is false. None, otherwise.
"""

logger.error(
msg, exc_info=(failure.type, failure.value, failure.getTracebackObject())
msg, exc_info=(failure.type, failure.value, failure.getTracebackObject()) # type: ignore[arg-type]
)

if not consumeErrors:
return failure
return None


def glob_to_regex(glob: str, word_boundary: bool = False) -> Pattern:
Expand Down