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

Commit 6463244

Browse files
author
David Robertson
authored
Remove unused # type: ignores (#12531)
Over time we've begun to use newer versions of mypy, typeshed, stub packages---and of course we've improved our own annotations. This makes some type ignore comments no longer necessary. I have removed them. There was one exception: a module that imports `select.epoll`. The ignore is redundant on Linux, but I've kept it ignored for those of us who work on the source tree using not-Linux. (#11771) I'm more interested in the config line which enforces this. I want unused ignores to be reported, because I think it's useful feedback when annotating to know when you've fixed a problem you had to previously ignore. * Installing extras before typechecking Lacking an easy way to install all extras generically, let's bite the bullet and make install the hand-maintained `all` extra before typechecking. Now that matrix-org/backend-meta#6 is merged to the release/v1 branch.
1 parent 8a23bde commit 6463244

File tree

21 files changed

+60
-57
lines changed

21 files changed

+60
-57
lines changed

.github/workflows/tests.yml

+2-6
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,9 @@ jobs:
2020
- run: scripts-dev/config-lint.sh
2121

2222
lint:
23-
# This does a vanilla `poetry install` - no extras. I'm slightly anxious
24-
# that we might skip some typechecks on code that uses extras. However,
25-
# I think the right way to fix this is to mark any extras needed for
26-
# typechecking as development dependencies. To detect this, we ought to
27-
# turn up mypy's strictness: disallow unknown imports and be accept fewer
28-
# uses of `Any`.
2923
uses: "matrix-org/backend-meta/.github/workflows/python-poetry-ci.yml@v1"
24+
with:
25+
typechecking-extras: "all"
3026

3127
lint-crlf:
3228
runs-on: ubuntu-latest

changelog.d/12531.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Remove unused `# type: ignore`s.

mypy.ini

+6
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ show_error_codes = True
77
show_traceback = True
88
mypy_path = stubs
99
warn_unreachable = True
10+
warn_unused_ignores = True
1011
local_partial_types = True
1112
no_implicit_optional = True
1213

@@ -134,6 +135,11 @@ disallow_untyped_defs = True
134135
[mypy-synapse.metrics.*]
135136
disallow_untyped_defs = True
136137

138+
[mypy-synapse.metrics._reactor_metrics]
139+
# This module imports select.epoll. That exists on Linux, but doesn't on macOS.
140+
# See https://github.com/matrix-org/synapse/pull/11771.
141+
warn_unused_ignores = False
142+
137143
[mypy-synapse.module_api.*]
138144
disallow_untyped_defs = True
139145

stubs/sortedcontainers/sorteddict.pyi

+1-3
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,7 @@ class SortedKeysView(KeysView[_KT_co], Sequence[_KT_co]):
115115
def __getitem__(self, index: slice) -> List[_KT_co]: ...
116116
def __delitem__(self, index: Union[int, slice]) -> None: ...
117117

118-
class SortedItemsView( # type: ignore
119-
ItemsView[_KT_co, _VT_co], Sequence[Tuple[_KT_co, _VT_co]]
120-
):
118+
class SortedItemsView(ItemsView[_KT_co, _VT_co], Sequence[Tuple[_KT_co, _VT_co]]):
121119
def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ...
122120
@overload
123121
def __getitem__(self, index: int) -> Tuple[_KT_co, _VT_co]: ...

synapse/app/_base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@
4848
from twisted.protocols.tls import TLSMemoryBIOFactory
4949
from twisted.python.threadpool import ThreadPool
5050

51-
import synapse
5251
from synapse.api.constants import MAX_PDU_SIZE
5352
from synapse.app import check_bind_error
5453
from synapse.app.phone_stats_home import start_phone_stats_home
@@ -60,6 +59,7 @@
6059
from synapse.events.third_party_rules import load_legacy_third_party_event_rules
6160
from synapse.handlers.auth import load_legacy_password_auth_providers
6261
from synapse.logging.context import PreserveLoggingContext
62+
from synapse.logging.opentracing import init_tracer
6363
from synapse.metrics import install_gc_manager, register_threadpool
6464
from synapse.metrics.background_process_metrics import wrap_as_background_process
6565
from synapse.metrics.jemalloc import setup_jemalloc_stats
@@ -431,7 +431,7 @@ def run_sighup(*args: Any, **kwargs: Any) -> None:
431431
refresh_certificate(hs)
432432

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

436436
# Instantiate the modules so they can register their web resources to the module API
437437
# before we start the listeners.

synapse/config/server.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ def generate_ip_set(
186186
class HttpResourceConfig:
187187
names: List[str] = attr.ib(
188188
factory=list,
189-
validator=attr.validators.deep_iterable(attr.validators.in_(KNOWN_RESOURCES)), # type: ignore
189+
validator=attr.validators.deep_iterable(attr.validators.in_(KNOWN_RESOURCES)),
190190
)
191191
compress: bool = attr.ib(
192192
default=False,
@@ -231,9 +231,7 @@ class ManholeConfig:
231231
class LimitRemoteRoomsConfig:
232232
enabled: bool = attr.ib(validator=attr.validators.instance_of(bool), default=False)
233233
complexity: Union[float, int] = attr.ib(
234-
validator=attr.validators.instance_of(
235-
(float, int) # type: ignore[arg-type] # noqa
236-
),
234+
validator=attr.validators.instance_of((float, int)), # noqa
237235
default=1.0,
238236
)
239237
complexity_error: str = attr.ib(

synapse/federation/federation_server.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -268,8 +268,8 @@ async def on_incoming_transaction(
268268
transaction_id=transaction_id,
269269
destination=destination,
270270
origin=origin,
271-
origin_server_ts=transaction_data.get("origin_server_ts"), # type: ignore
272-
pdus=transaction_data.get("pdus"), # type: ignore
271+
origin_server_ts=transaction_data.get("origin_server_ts"), # type: ignore[arg-type]
272+
pdus=transaction_data.get("pdus"),
273273
edus=transaction_data.get("edus"),
274274
)
275275

synapse/federation/transport/client.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -229,21 +229,21 @@ async def send_transaction(
229229
"""
230230
logger.debug(
231231
"send_data dest=%s, txid=%s",
232-
transaction.destination, # type: ignore
233-
transaction.transaction_id, # type: ignore
232+
transaction.destination,
233+
transaction.transaction_id,
234234
)
235235

236-
if transaction.destination == self.server_name: # type: ignore
236+
if transaction.destination == self.server_name:
237237
raise RuntimeError("Transport layer cannot send to itself!")
238238

239239
# FIXME: This is only used by the tests. The actual json sent is
240240
# generated by the json_data_callback.
241241
json_data = transaction.get_dict()
242242

243-
path = _create_v1_path("/send/%s", transaction.transaction_id) # type: ignore
243+
path = _create_v1_path("/send/%s", transaction.transaction_id)
244244

245245
return await self.client.put_json(
246-
transaction.destination, # type: ignore
246+
transaction.destination,
247247
path=path,
248248
data=json_data,
249249
json_data_callback=json_data_callback,

synapse/handlers/auth.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ async def check_ui_auth(
481481
sid = authdict["session"]
482482

483483
# Convert the URI and method to strings.
484-
uri = request.uri.decode("utf-8") # type: ignore
484+
uri = request.uri.decode("utf-8")
485485
method = request.method.decode("utf-8")
486486

487487
# If there's no session ID, create a new session.

synapse/handlers/oidc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -966,7 +966,7 @@ async def oidc_response_to_user_attributes(failures: int) -> UserAttributes:
966966
"Mapping provider does not support de-duplicating Matrix IDs"
967967
)
968968

969-
attributes = await self._user_mapping_provider.map_user_attributes( # type: ignore
969+
attributes = await self._user_mapping_provider.map_user_attributes(
970970
userinfo, token
971971
)
972972

synapse/handlers/search.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ async def _search(
357357
itertools.chain(
358358
# The events_before and events_after for each context.
359359
itertools.chain.from_iterable(
360-
itertools.chain(context["events_before"], context["events_after"]) # type: ignore[arg-type]
360+
itertools.chain(context["events_before"], context["events_after"])
361361
for context in contexts.values()
362362
),
363363
# The returned events.
@@ -373,10 +373,10 @@ async def _search(
373373

374374
for context in contexts.values():
375375
context["events_before"] = self._event_serializer.serialize_events(
376-
context["events_before"], time_now, bundle_aggregations=aggregations # type: ignore[arg-type]
376+
context["events_before"], time_now, bundle_aggregations=aggregations
377377
)
378378
context["events_after"] = self._event_serializer.serialize_events(
379-
context["events_after"], time_now, bundle_aggregations=aggregations # type: ignore[arg-type]
379+
context["events_after"], time_now, bundle_aggregations=aggregations
380380
)
381381

382382
results = [

synapse/http/server.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ async def _async_render(self, request: SynapseRequest) -> Optional[Tuple[int, An
295295
if isawaitable(raw_callback_return):
296296
callback_return = await raw_callback_return
297297
else:
298-
callback_return = raw_callback_return # type: ignore
298+
callback_return = raw_callback_return
299299

300300
return callback_return
301301

@@ -469,7 +469,7 @@ async def _async_render(self, request: SynapseRequest) -> Tuple[int, Any]:
469469
if isinstance(raw_callback_return, (defer.Deferred, types.CoroutineType)):
470470
callback_return = await raw_callback_return
471471
else:
472-
callback_return = raw_callback_return # type: ignore
472+
callback_return = raw_callback_return
473473

474474
return callback_return
475475

synapse/module_api/__init__.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@
109109
from synapse.types import (
110110
DomainSpecificString,
111111
JsonDict,
112+
JsonMapping,
112113
Requester,
113114
StateMap,
114115
UserID,
@@ -151,6 +152,7 @@
151152
"PRESENCE_ALL_USERS",
152153
"LoginResponse",
153154
"JsonDict",
155+
"JsonMapping",
154156
"EventBase",
155157
"StateMap",
156158
"ProfileInfo",
@@ -1419,7 +1421,7 @@ def _validate_user_id(self, user_id: str) -> None:
14191421
f"{user_id} is not local to this homeserver; can't access account data for remote users."
14201422
)
14211423

1422-
async def get_global(self, user_id: str, data_type: str) -> Optional[JsonDict]:
1424+
async def get_global(self, user_id: str, data_type: str) -> Optional[JsonMapping]:
14231425
"""
14241426
Gets some global account data, of a specified type, for the specified user.
14251427

synapse/storage/databases/main/monthly_active_users.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -232,10 +232,10 @@ def _reap_users(txn: LoggingTransaction, reserved_users: List[str]) -> None:
232232
# is racy.
233233
# Have resolved to invalidate the whole cache for now and do
234234
# something about it if and when the perf becomes significant
235-
self._invalidate_all_cache_and_stream( # type: ignore[attr-defined]
235+
self._invalidate_all_cache_and_stream(
236236
txn, self.user_last_seen_monthly_active
237237
)
238-
self._invalidate_cache_and_stream(txn, self.get_monthly_active_count, ()) # type: ignore[attr-defined]
238+
self._invalidate_cache_and_stream(txn, self.get_monthly_active_count, ())
239239

240240
reserved_users = await self.get_registered_reserved_users()
241241
await self.db_pool.runInteraction(
@@ -363,7 +363,7 @@ async def populate_monthly_active_users(self, user_id: str) -> None:
363363

364364
if self._limit_usage_by_mau or self._mau_stats_only:
365365
# Trial users and guests should not be included as part of MAU group
366-
is_guest = await self.is_guest(user_id) # type: ignore[attr-defined]
366+
is_guest = await self.is_guest(user_id)
367367
if is_guest:
368368
return
369369
is_trial = await self.is_trial_user(user_id)

synapse/storage/prepare_database.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -501,11 +501,11 @@ def _upgrade_existing_database(
501501

502502
if hasattr(module, "run_create"):
503503
logger.info("Running %s:run_create", relative_path)
504-
module.run_create(cur, database_engine) # type: ignore
504+
module.run_create(cur, database_engine)
505505

506506
if not is_empty and hasattr(module, "run_upgrade"):
507507
logger.info("Running %s:run_upgrade", relative_path)
508-
module.run_upgrade(cur, database_engine, config=config) # type: ignore
508+
module.run_upgrade(cur, database_engine, config=config)
509509
elif ext == ".pyc" or file_name == "__pycache__":
510510
# Sometimes .pyc files turn up anyway even though we've
511511
# disabled their generation; e.g. from distribution package

synapse/util/caches/ttlcache.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def get_with_expiry(self, key: KT) -> Tuple[VT, float, float]:
107107
self._metrics.inc_hits()
108108
return e.value, e.expiry_time, e.ttl
109109

110-
def pop(self, key: KT, default: T = SENTINEL) -> Union[VT, T]: # type: ignore
110+
def pop(self, key: KT, default: T = SENTINEL) -> Union[VT, T]:
111111
"""Remove a value from the cache
112112
113113
If key is in the cache, remove it and return its value, else return default.

tests/handlers/test_register.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -193,26 +193,23 @@ def test_mau_limits_when_disabled(self):
193193

194194
@override_config({"limit_usage_by_mau": True})
195195
def test_get_or_create_user_mau_not_blocked(self):
196-
# Type ignore: mypy doesn't like us assigning to methods.
197-
self.store.count_monthly_users = Mock( # type: ignore[assignment]
196+
self.store.count_monthly_users = Mock(
198197
return_value=make_awaitable(self.hs.config.server.max_mau_value - 1)
199198
)
200199
# Ensure does not throw exception
201200
self.get_success(self.get_or_create_user(self.requester, "c", "User"))
202201

203202
@override_config({"limit_usage_by_mau": True})
204203
def test_get_or_create_user_mau_blocked(self):
205-
# Type ignore: mypy doesn't like us assigning to methods.
206-
self.store.get_monthly_active_count = Mock( # type: ignore[assignment]
204+
self.store.get_monthly_active_count = Mock(
207205
return_value=make_awaitable(self.lots_of_users)
208206
)
209207
self.get_failure(
210208
self.get_or_create_user(self.requester, "b", "display_name"),
211209
ResourceLimitError,
212210
)
213211

214-
# Type ignore: mypy doesn't like us assigning to methods.
215-
self.store.get_monthly_active_count = Mock( # type: ignore[assignment]
212+
self.store.get_monthly_active_count = Mock(
216213
return_value=make_awaitable(self.hs.config.server.max_mau_value)
217214
)
218215
self.get_failure(

tests/module_api/test_account_data_manager.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,12 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
from twisted.test.proto_helpers import MemoryReactor
15+
1416
from synapse.api.errors import SynapseError
1517
from synapse.rest import admin
18+
from synapse.server import HomeServer
19+
from synapse.util import Clock
1620

1721
from tests.unittest import HomeserverTestCase
1822

@@ -22,7 +26,9 @@ class ModuleApiTestCase(HomeserverTestCase):
2226
admin.register_servlets,
2327
]
2428

25-
def prepare(self, reactor, clock, homeserver) -> None:
29+
def prepare(
30+
self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
31+
) -> None:
2632
self._store = homeserver.get_datastores().main
2733
self._module_api = homeserver.get_module_api()
2834
self._account_data_mgr = self._module_api.account_data_manager
@@ -91,7 +97,7 @@ def test_get_global_no_mutability(self) -> None:
9197
)
9298
with self.assertRaises(TypeError):
9399
# This throws an exception because it's a frozen dict.
94-
the_data["wombat"] = False
100+
the_data["wombat"] = False # type: ignore[index]
95101

96102
def test_put_global(self) -> None:
97103
"""
@@ -143,15 +149,14 @@ def test_put_global_validation(self) -> None:
143149
with self.assertRaises(TypeError):
144150
# The account data type must be a string.
145151
self.get_success_or_raise(
146-
self._module_api.account_data_manager.put_global(
147-
self.user_id, 42, {} # type: ignore
148-
)
152+
self._module_api.account_data_manager.put_global(self.user_id, 42, {}) # type: ignore[arg-type]
149153
)
150154

151155
with self.assertRaises(TypeError):
152156
# The account data dict must be a dict.
157+
# noinspection PyTypeChecker
153158
self.get_success_or_raise(
154159
self._module_api.account_data_manager.put_global(
155-
self.user_id, "test.data", 42 # type: ignore
160+
self.user_id, "test.data", 42 # type: ignore[arg-type]
156161
)
157162
)

tests/replication/test_federation_sender_shard.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,8 @@ def test_send_event_sharded(self):
102102
for i in range(20):
103103
server_name = "other_server_%d" % (i,)
104104
room = self.create_room_with_remote_server(user, token, server_name)
105-
mock_client1.reset_mock() # type: ignore[attr-defined]
106-
mock_client2.reset_mock() # type: ignore[attr-defined]
105+
mock_client1.reset_mock()
106+
mock_client2.reset_mock()
107107

108108
self.create_and_send_event(room, UserID.from_string(user))
109109
self.replicate()
@@ -167,8 +167,8 @@ def test_send_typing_sharded(self):
167167
for i in range(20):
168168
server_name = "other_server_%d" % (i,)
169169
room = self.create_room_with_remote_server(user, token, server_name)
170-
mock_client1.reset_mock() # type: ignore[attr-defined]
171-
mock_client2.reset_mock() # type: ignore[attr-defined]
170+
mock_client1.reset_mock()
171+
mock_client2.reset_mock()
172172

173173
self.get_success(
174174
typing_handler.started_typing(

tests/test_utils/__init__.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def make_awaitable(result: TV) -> Awaitable[TV]:
5252
This uses Futures as they can be awaited multiple times so can be returned
5353
to multiple callers.
5454
"""
55-
future = Future() # type: ignore
55+
future: Future[TV] = Future()
5656
future.set_result(result)
5757
return future
5858

@@ -69,7 +69,7 @@ def setup_awaitable_errors() -> Callable[[], None]:
6969

7070
# State shared between unraisablehook and check_for_unraisable_exceptions.
7171
unraisable_exceptions = []
72-
orig_unraisablehook = sys.unraisablehook # type: ignore
72+
orig_unraisablehook = sys.unraisablehook
7373

7474
def unraisablehook(unraisable):
7575
unraisable_exceptions.append(unraisable.exc_value)
@@ -78,11 +78,11 @@ def cleanup():
7878
"""
7979
A method to be used as a clean-up that fails a test-case if there are any new unraisable exceptions.
8080
"""
81-
sys.unraisablehook = orig_unraisablehook # type: ignore
81+
sys.unraisablehook = orig_unraisablehook
8282
if unraisable_exceptions:
8383
raise unraisable_exceptions.pop()
8484

85-
sys.unraisablehook = unraisablehook # type: ignore
85+
sys.unraisablehook = unraisablehook
8686

8787
return cleanup
8888

0 commit comments

Comments
 (0)