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

Commit c01343d

Browse files
authored
Add stricter mypy options (#15694)
Enable warn_unused_configs, strict_concatenate, disallow_subclassing_any, and disallow_incomplete_defs.
1 parent 6fc3deb commit c01343d

File tree

11 files changed

+40
-24
lines changed

11 files changed

+40
-24
lines changed

changelog.d/15694.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve type hints.

mypy.ini

+20-3
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,29 @@
22
namespace_packages = True
33
plugins = pydantic.mypy, mypy_zope:plugin, scripts-dev/mypy_synapse_plugin.py
44
follow_imports = normal
5-
check_untyped_defs = True
65
show_error_codes = True
76
show_traceback = True
87
mypy_path = stubs
98
warn_unreachable = True
10-
warn_unused_ignores = True
119
local_partial_types = True
1210
no_implicit_optional = True
11+
12+
# Strict checks, see mypy --help
13+
warn_unused_configs = True
14+
# disallow_any_generics = True
15+
disallow_subclassing_any = True
16+
# disallow_untyped_calls = True
1317
disallow_untyped_defs = True
14-
strict_equality = True
18+
disallow_incomplete_defs = True
19+
# check_untyped_defs = True
20+
# disallow_untyped_decorators = True
1521
warn_redundant_casts = True
22+
warn_unused_ignores = True
23+
# warn_return_any = True
24+
# no_implicit_reexport = True
25+
strict_equality = True
26+
strict_concatenate = True
27+
1628
# Run mypy type checking with the minimum supported Python version to catch new usage
1729
# that isn't backwards-compatible (types, overloads, etc).
1830
python_version = 3.8
@@ -31,6 +43,7 @@ warn_unused_ignores = False
3143

3244
[mypy-synapse.util.caches.treecache]
3345
disallow_untyped_defs = False
46+
disallow_incomplete_defs = False
3447

3548
;; Dependencies without annotations
3649
;; Before ignoring a module, check to see if type stubs are available.
@@ -40,6 +53,7 @@ disallow_untyped_defs = False
4053
;; which we can pull in as a dev dependency by adding to `pyproject.toml`'s
4154
;; `[tool.poetry.dev-dependencies]` list.
4255

56+
# https://github.com/lepture/authlib/issues/460
4357
[mypy-authlib.*]
4458
ignore_missing_imports = True
4559

@@ -49,9 +63,11 @@ ignore_missing_imports = True
4963
[mypy-lxml]
5064
ignore_missing_imports = True
5165

66+
# https://github.com/msgpack/msgpack-python/issues/448
5267
[mypy-msgpack]
5368
ignore_missing_imports = True
5469

70+
# https://github.com/wolever/parameterized/issues/143
5571
[mypy-parameterized.*]
5672
ignore_missing_imports = True
5773

@@ -73,6 +89,7 @@ ignore_missing_imports = True
7389
[mypy-srvlookup.*]
7490
ignore_missing_imports = True
7591

92+
# https://github.com/twisted/treq/pull/366
7693
[mypy-treq.*]
7794
ignore_missing_imports = True
7895

synapse/api/auth/msc3861_delegated.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def scope_to_list(scope: str) -> List[str]:
5959
return scope.strip().split(" ")
6060

6161

62-
class PrivateKeyJWTWithKid(PrivateKeyJWT):
62+
class PrivateKeyJWTWithKid(PrivateKeyJWT): # type: ignore[misc]
6363
"""An implementation of the private_key_jwt client auth method that includes a kid header.
6464
6565
This is needed because some providers (Keycloak) require the kid header to figure

synapse/federation/federation_server.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -515,7 +515,7 @@ async def process_pdu(pdu: EventBase) -> JsonDict:
515515
logger.error(
516516
"Failed to handle PDU %s",
517517
event_id,
518-
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
518+
exc_info=(f.type, f.value, f.getTracebackObject()),
519519
)
520520
return {"error": str(e)}
521521

@@ -1247,7 +1247,7 @@ async def _process_incoming_pdus_in_room_inner(
12471247
logger.error(
12481248
"Failed to handle PDU %s",
12491249
event.event_id,
1250-
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
1250+
exc_info=(f.type, f.value, f.getTracebackObject()),
12511251
)
12521252

12531253
received_ts = await self.store.remove_received_event_from_staging(

synapse/handlers/oidc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1354,7 +1354,7 @@ async def handle_backchannel_logout(
13541354
finish_request(request)
13551355

13561356

1357-
class LogoutToken(JWTClaims):
1357+
class LogoutToken(JWTClaims): # type: ignore[misc]
13581358
"""
13591359
Holds and verify claims of a logout token, as per
13601360
https://openid.net/specs/openid-connect-backchannel-1_0.html#LogoutToken

synapse/handlers/pagination.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ async def _purge_history(
360360
except Exception:
361361
f = Failure()
362362
logger.error(
363-
"[purge] failed", exc_info=(f.type, f.value, f.getTracebackObject()) # type: ignore
363+
"[purge] failed", exc_info=(f.type, f.value, f.getTracebackObject())
364364
)
365365
self._purges_by_id[purge_id].status = PurgeStatus.STATUS_FAILED
366366
self._purges_by_id[purge_id].error = f.getErrorMessage()
@@ -689,7 +689,7 @@ async def _shutdown_and_purge_room(
689689
f = Failure()
690690
logger.error(
691691
"failed",
692-
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
692+
exc_info=(f.type, f.value, f.getTracebackObject()),
693693
)
694694
self._delete_by_id[delete_id].status = DeleteStatus.STATUS_FAILED
695695
self._delete_by_id[delete_id].error = f.getErrorMessage()

synapse/http/server.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def return_json_error(
108108

109109
if f.check(SynapseError):
110110
# mypy doesn't understand that f.check asserts the type.
111-
exc: SynapseError = f.value # type: ignore
111+
exc: SynapseError = f.value
112112
error_code = exc.code
113113
error_dict = exc.error_dict(config)
114114
if exc.headers is not None:
@@ -124,7 +124,7 @@ def return_json_error(
124124
"Got cancellation before client disconnection from %r: %r",
125125
request.request_metrics.name,
126126
request,
127-
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
127+
exc_info=(f.type, f.value, f.getTracebackObject()),
128128
)
129129
else:
130130
error_code = 500
@@ -134,7 +134,7 @@ def return_json_error(
134134
"Failed handle request via %r: %r",
135135
request.request_metrics.name,
136136
request,
137-
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
137+
exc_info=(f.type, f.value, f.getTracebackObject()),
138138
)
139139

140140
# Only respond with an error response if we haven't already started writing,
@@ -172,7 +172,7 @@ def return_html_error(
172172
"""
173173
if f.check(CodeMessageException):
174174
# mypy doesn't understand that f.check asserts the type.
175-
cme: CodeMessageException = f.value # type: ignore
175+
cme: CodeMessageException = f.value
176176
code = cme.code
177177
msg = cme.msg
178178
if cme.headers is not None:
@@ -189,7 +189,7 @@ def return_html_error(
189189
logger.error(
190190
"Failed handle request %r",
191191
request,
192-
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
192+
exc_info=(f.type, f.value, f.getTracebackObject()),
193193
)
194194
elif f.check(CancelledError):
195195
code = HTTP_STATUS_REQUEST_CANCELLED
@@ -199,7 +199,7 @@ def return_html_error(
199199
logger.error(
200200
"Got cancellation before client disconnection when handling request %r",
201201
request,
202-
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
202+
exc_info=(f.type, f.value, f.getTracebackObject()),
203203
)
204204
else:
205205
code = HTTPStatus.INTERNAL_SERVER_ERROR
@@ -208,7 +208,7 @@ def return_html_error(
208208
logger.error(
209209
"Failed handle request %r",
210210
request,
211-
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
211+
exc_info=(f.type, f.value, f.getTracebackObject()),
212212
)
213213

214214
if isinstance(error_template, str):

synapse/util/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def unwrapFirstError(failure: Failure) -> Failure:
7676
# the subFailure's value, which will do a better job of preserving stacktraces.
7777
# (actually, you probably want to use yieldable_gather_results anyway)
7878
failure.trap(defer.FirstError)
79-
return failure.value.subFailure # type: ignore[union-attr] # Issue in Twisted's annotations
79+
return failure.value.subFailure
8080

8181

8282
P = ParamSpec("P")
@@ -178,7 +178,7 @@ def log_failure(
178178
"""
179179

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

184184
if not consumeErrors:

synapse/util/async_helpers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ def errback(f: Failure) -> Optional[Failure]:
138138
for observer in observers:
139139
# This is a little bit of magic to correctly propagate stack
140140
# traces when we `await` on one of the observer deferreds.
141-
f.value.__failure__ = f # type: ignore[union-attr]
141+
f.value.__failure__ = f
142142
try:
143143
observer.errback(f)
144144
except Exception as e:

synapse/util/caches/lrucache.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,8 @@ def _get_size_of(val: Any, *, recurse: bool = True) -> int:
9393
# a general type var, distinct from either KT or VT
9494
T = TypeVar("T")
9595

96-
P = TypeVar("P")
9796

98-
99-
class _TimedListNode(ListNode[P]):
97+
class _TimedListNode(ListNode[T]):
10098
"""A `ListNode` that tracks last access time."""
10199

102100
__slots__ = ["last_access_ts_secs"]
@@ -821,7 +819,7 @@ class AsyncLruCache(Generic[KT, VT]):
821819
utilize external cache systems that require await behaviour to be created.
822820
"""
823821

824-
def __init__(self, *args, **kwargs): # type: ignore
822+
def __init__(self, *args: Any, **kwargs: Any):
825823
self._lru_cache: LruCache[KT, VT] = LruCache(*args, **kwargs)
826824

827825
async def get(

tests/server.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -642,7 +642,7 @@ def runInteraction(
642642
pool.runWithConnection = runWithConnection # type: ignore[assignment]
643643
pool.runInteraction = runInteraction # type: ignore[assignment]
644644
# Replace the thread pool with a threadless 'thread' pool
645-
pool.threadpool = ThreadPool(clock._reactor) # type: ignore[assignment]
645+
pool.threadpool = ThreadPool(clock._reactor)
646646
pool.running = True
647647

648648
# We've just changed the Databases to run DB transactions on the same

0 commit comments

Comments
 (0)