Add more type hints to synapse.util. (#11321)

This commit is contained in:
Patrick Cloke 2021-11-12 08:43:06 -05:00 committed by GitHub
parent 2fffcb24d8
commit b64b6d12d4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 15 deletions

1
changelog.d/11321.misc Normal file
View File

@ -0,0 +1 @@
Add type hints to `synapse.util`.

View File

@ -98,7 +98,7 @@ def return_json_error(f: failure.Failure, request: SynapseRequest) -> None:
"Failed handle request via %r: %r", "Failed handle request via %r: %r",
request.request_metrics.name, request.request_metrics.name,
request, 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, # Only respond with an error response if we haven't already started writing,
@ -150,7 +150,7 @@ def return_html_error(
logger.error( logger.error(
"Failed handle request %r", "Failed handle request %r",
request, request,
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
) )
else: else:
code = HTTPStatus.INTERNAL_SERVER_ERROR code = HTTPStatus.INTERNAL_SERVER_ERROR
@ -159,7 +159,7 @@ def return_html_error(
logger.error( logger.error(
"Failed handle request %r", "Failed handle request %r",
request, 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): if isinstance(error_template, str):

View File

@ -16,7 +16,7 @@ import json
import logging import logging
import re import re
import typing import typing
from typing import Any, Callable, Dict, Generator, Pattern from typing import Any, Callable, Dict, Generator, Optional, Pattern
import attr import attr
from frozendict import frozendict from frozendict import frozendict
@ -110,7 +110,9 @@ class Clock:
"""Returns the current system time in milliseconds since epoch.""" """Returns the current system time in milliseconds since epoch."""
return int(self.time() * 1000) 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. """Call a function repeatedly.
Waits `msec` initially before calling `f` for the first time. Waits `msec` initially before calling `f` for the first time.
@ -130,20 +132,22 @@ class Clock:
d.addErrback(log_failure, "Looping call died", consumeErrors=False) d.addErrback(log_failure, "Looping call died", consumeErrors=False)
return call 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 """Call something later
Note that the function will be called with no logcontext, so if it is anything 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. other than trivial, you probably want to wrap it in run_as_background_process.
Args: Args:
delay(float): How long to wait in seconds. delay: How long to wait in seconds.
callback(function): Function to call callback: Function to call
*args: Postional arguments to pass to function. *args: Postional arguments to pass to function.
**kwargs: Key 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(): with context.PreserveLoggingContext():
callback(*args, **kwargs) callback(*args, **kwargs)
@ -158,25 +162,29 @@ class Clock:
raise 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 """Creates a function suitable for passing to `Deferred.addErrback` that
logs any failures that occur. logs any failures that occur.
Args: Args:
msg (str): Message to log failure: The Failure to log
consumeErrors (bool): If true consumes the failure, otherwise passes msg: Message to log
on down the callback chain consumeErrors: If true consumes the failure, otherwise passes on down
the callback chain
Returns: Returns:
func(Failure) The Failure if consumeErrors is false. None, otherwise.
""" """
logger.error( 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: if not consumeErrors:
return failure return failure
return None
def glob_to_regex(glob: str, word_boundary: bool = False) -> Pattern: def glob_to_regex(glob: str, word_boundary: bool = False) -> Pattern: