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

Commit aec294e

Browse files
authored
Use slots in attrs classes where possible (#8296)
slots use less memory (and attribute access is faster) while slightly limiting the flexibility of the class attributes. This focuses on objects which are instantiated "often" and for short periods of time.
1 parent d2a3eb0 commit aec294e

22 files changed

+33
-50
lines changed

changelog.d/8296.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Use slotted classes where possible.

synapse/handlers/acme_issuing_service.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def create_issuing_service(reactor, acme_url, account_key_file, well_known_resou
7676
)
7777

7878

79-
@attr.s
79+
@attr.s(slots=True)
8080
@implementer(ICertificateStore)
8181
class ErsatzStore:
8282
"""

synapse/handlers/auth.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1235,7 +1235,7 @@ def add_query_param_to_url(url: str, param_name: str, param: Any):
12351235
return urllib.parse.urlunparse(url_parts)
12361236

12371237

1238-
@attr.s
1238+
@attr.s(slots=True)
12391239
class MacaroonGenerator:
12401240

12411241
hs = attr.ib()

synapse/handlers/e2e_keys.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1201,7 +1201,7 @@ def _one_time_keys_match(old_key_json, new_key):
12011201
return old_key == new_key_copy
12021202

12031203

1204-
@attr.s
1204+
@attr.s(slots=True)
12051205
class SignatureListItem:
12061206
"""An item in the signature list as used by upload_signatures_for_device_keys.
12071207
"""

synapse/handlers/federation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@
8686
logger = logging.getLogger(__name__)
8787

8888

89-
@attr.s
89+
@attr.s(slots=True)
9090
class _NewEventInfo:
9191
"""Holds information about a received event, ready for passing to _handle_new_events
9292

synapse/handlers/saml_handler.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ class MappingException(Exception):
4646
"""Used to catch errors when mapping the SAML2 response to a user."""
4747

4848

49-
@attr.s
49+
@attr.s(slots=True)
5050
class Saml2SessionData:
5151
"""Data we track about SAML2 sessions"""
5252

synapse/handlers/sync.py

+10-24
Original file line numberDiff line numberDiff line change
@@ -89,14 +89,12 @@ class TimelineBatch:
8989
events = attr.ib(type=List[EventBase])
9090
limited = attr.ib(bool)
9191

92-
def __nonzero__(self) -> bool:
92+
def __bool__(self) -> bool:
9393
"""Make the result appear empty if there are no updates. This is used
9494
to tell if room needs to be part of the sync result.
9595
"""
9696
return bool(self.events)
9797

98-
__bool__ = __nonzero__ # python3
99-
10098

10199
# We can't freeze this class, because we need to update it after it's instantiated to
102100
# update its unread count. This is because we calculate the unread count for a room only
@@ -114,7 +112,7 @@ class JoinedSyncResult:
114112
summary = attr.ib(type=Optional[JsonDict])
115113
unread_count = attr.ib(type=int)
116114

117-
def __nonzero__(self) -> bool:
115+
def __bool__(self) -> bool:
118116
"""Make the result appear empty if there are no updates. This is used
119117
to tell if room needs to be part of the sync result.
120118
"""
@@ -127,8 +125,6 @@ def __nonzero__(self) -> bool:
127125
# else in the result, we don't need to send it.
128126
)
129127

130-
__bool__ = __nonzero__ # python3
131-
132128

133129
@attr.s(slots=True, frozen=True)
134130
class ArchivedSyncResult:
@@ -137,38 +133,32 @@ class ArchivedSyncResult:
137133
state = attr.ib(type=StateMap[EventBase])
138134
account_data = attr.ib(type=List[JsonDict])
139135

140-
def __nonzero__(self) -> bool:
136+
def __bool__(self) -> bool:
141137
"""Make the result appear empty if there are no updates. This is used
142138
to tell if room needs to be part of the sync result.
143139
"""
144140
return bool(self.timeline or self.state or self.account_data)
145141

146-
__bool__ = __nonzero__ # python3
147-
148142

149143
@attr.s(slots=True, frozen=True)
150144
class InvitedSyncResult:
151145
room_id = attr.ib(type=str)
152146
invite = attr.ib(type=EventBase)
153147

154-
def __nonzero__(self) -> bool:
148+
def __bool__(self) -> bool:
155149
"""Invited rooms should always be reported to the client"""
156150
return True
157151

158-
__bool__ = __nonzero__ # python3
159-
160152

161153
@attr.s(slots=True, frozen=True)
162154
class GroupsSyncResult:
163155
join = attr.ib(type=JsonDict)
164156
invite = attr.ib(type=JsonDict)
165157
leave = attr.ib(type=JsonDict)
166158

167-
def __nonzero__(self) -> bool:
159+
def __bool__(self) -> bool:
168160
return bool(self.join or self.invite or self.leave)
169161

170-
__bool__ = __nonzero__ # python3
171-
172162

173163
@attr.s(slots=True, frozen=True)
174164
class DeviceLists:
@@ -181,13 +171,11 @@ class DeviceLists:
181171
changed = attr.ib(type=Collection[str])
182172
left = attr.ib(type=Collection[str])
183173

184-
def __nonzero__(self) -> bool:
174+
def __bool__(self) -> bool:
185175
return bool(self.changed or self.left)
186176

187-
__bool__ = __nonzero__ # python3
188177

189-
190-
@attr.s
178+
@attr.s(slots=True)
191179
class _RoomChanges:
192180
"""The set of room entries to include in the sync, plus the set of joined
193181
and left room IDs since last sync.
@@ -227,7 +215,7 @@ class SyncResult:
227215
device_one_time_keys_count = attr.ib(type=JsonDict)
228216
groups = attr.ib(type=Optional[GroupsSyncResult])
229217

230-
def __nonzero__(self) -> bool:
218+
def __bool__(self) -> bool:
231219
"""Make the result appear empty if there are no updates. This is used
232220
to tell if the notifier needs to wait for more events when polling for
233221
events.
@@ -243,8 +231,6 @@ def __nonzero__(self) -> bool:
243231
or self.groups
244232
)
245233

246-
__bool__ = __nonzero__ # python3
247-
248234

249235
class SyncHandler:
250236
def __init__(self, hs: "HomeServer"):
@@ -2038,7 +2024,7 @@ def _calculate_state(
20382024
return {event_id_to_key[e]: e for e in state_ids}
20392025

20402026

2041-
@attr.s
2027+
@attr.s(slots=True)
20422028
class SyncResultBuilder:
20432029
"""Used to help build up a new SyncResult for a user
20442030
@@ -2074,7 +2060,7 @@ class SyncResultBuilder:
20742060
to_device = attr.ib(type=List[JsonDict], default=attr.Factory(list))
20752061

20762062

2077-
@attr.s
2063+
@attr.s(slots=True)
20782064
class RoomSyncResultBuilder:
20792065
"""Stores information needed to create either a `JoinedSyncResult` or
20802066
`ArchivedSyncResult`.

synapse/http/federation/well_known_resolver.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ def _parse_cache_control(headers: Headers) -> Dict[bytes, Optional[bytes]]:
311311
return cache_controls
312312

313313

314-
@attr.s()
314+
@attr.s(slots=True)
315315
class _FetchWellKnownFailure(Exception):
316316
# True if we didn't get a non-5xx HTTP response, i.e. this may or may not be
317317
# a temporary failure.

synapse/http/matrixfederationclient.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@
7676
_next_id = 1
7777

7878

79-
@attr.s(frozen=True)
79+
@attr.s(slots=True, frozen=True)
8080
class MatrixFederationRequest:
8181
method = attr.ib()
8282
"""HTTP method

synapse/logging/context.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -217,11 +217,9 @@ def add_database_scheduled(self, sched_sec):
217217
def record_event_fetch(self, event_count):
218218
pass
219219

220-
def __nonzero__(self):
220+
def __bool__(self):
221221
return False
222222

223-
__bool__ = __nonzero__ # python3
224-
225223

226224
SENTINEL_CONTEXT = _Sentinel()
227225

synapse/metrics/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def collect():
5959
yield metric
6060

6161

62-
@attr.s(hash=True)
62+
@attr.s(slots=True, hash=True)
6363
class LaterGauge:
6464

6565
name = attr.ib(type=str)
@@ -205,7 +205,7 @@ def _register_with_collector(self):
205205
all_gauges[self.name] = self
206206

207207

208-
@attr.s(hash=True)
208+
@attr.s(slots=True, hash=True)
209209
class BucketCollector:
210210
"""
211211
Like a Histogram, but allows buckets to be point-in-time instead of

synapse/notifier.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -164,11 +164,9 @@ def new_listener(self, token: StreamToken) -> _NotificationListener:
164164

165165

166166
class EventStreamResult(namedtuple("EventStreamResult", ("events", "tokens"))):
167-
def __nonzero__(self):
167+
def __bool__(self):
168168
return bool(self.events)
169169

170-
__bool__ = __nonzero__ # python3
171-
172170

173171
class Notifier:
174172
""" This class is responsible for notifying any listeners when there are

synapse/replication/tcp/streams/_base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ class CachesStream(Stream):
383383
the cache on the workers
384384
"""
385385

386-
@attr.s
386+
@attr.s(slots=True)
387387
class CachesStreamRow:
388388
"""Stream to inform workers they should invalidate their cache.
389389
@@ -441,7 +441,7 @@ class DeviceListsStream(Stream):
441441
told about a device update.
442442
"""
443443

444-
@attr.s
444+
@attr.s(slots=True)
445445
class DeviceListsStreamRow:
446446
entity = attr.ib(type=str)
447447

synapse/rest/media/v1/preview_url_resource.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@
102102
_oembed_patterns[re.compile(pattern)] = endpoint
103103

104104

105-
@attr.s
105+
@attr.s(slots=True)
106106
class OEmbedResult:
107107
# Either HTML content or URL must be provided.
108108
html = attr.ib(type=Optional[str])

synapse/state/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -678,7 +678,7 @@ def resolve_events_with_store(
678678
)
679679

680680

681-
@attr.s
681+
@attr.s(slots=True)
682682
class StateResolutionStore:
683683
"""Interface that allows state resolution algorithms to access the database
684684
in well defined way.

synapse/storage/databases/main/end_to_end_keys.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
from synapse.handlers.e2e_keys import SignatureListItem
3636

3737

38-
@attr.s
38+
@attr.s(slots=True)
3939
class DeviceKeyLookupResult:
4040
"""The type returned by get_e2e_device_keys_and_signatures"""
4141

synapse/storage/databases/main/event_push_actions.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -969,7 +969,7 @@ def _action_has_highlight(actions):
969969
return False
970970

971971

972-
@attr.s
972+
@attr.s(slots=True)
973973
class _EventPushSummary:
974974
"""Summary of pending event push actions for a given user in a given room.
975975
Used in _rotate_notifs_before_txn to manipulate results from event_push_actions.

synapse/storage/databases/main/ui_auth.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from synapse.util import json_encoder, stringutils
2424

2525

26-
@attr.s
26+
@attr.s(slots=True)
2727
class UIAuthSessionData:
2828
session_id = attr.ib(type=str)
2929
# The dictionary from the client root level, not the 'auth' key.

synapse/storage/prepare_database.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -638,7 +638,7 @@ def _get_or_create_schema_state(txn, database_engine):
638638
return None
639639

640640

641-
@attr.s()
641+
@attr.s(slots=True)
642642
class _DirectoryListing:
643643
"""Helper class to store schema file name and the
644644
absolute path to it.

synapse/storage/relations.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
logger = logging.getLogger(__name__)
2323

2424

25-
@attr.s
25+
@attr.s(slots=True)
2626
class PaginationChunk:
2727
"""Returned by relation pagination APIs.
2828

synapse/util/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def unwrapFirstError(failure):
4545
return failure.value.subFailure
4646

4747

48-
@attr.s
48+
@attr.s(slots=True)
4949
class Clock:
5050
"""
5151
A Clock wraps a Twisted reactor and provides utilities on top of it.

synapse/util/caches/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
response_cache_total = Gauge("synapse_util_caches_response_cache:total", "", ["name"])
4343

4444

45-
@attr.s
45+
@attr.s(slots=True)
4646
class CacheMetric:
4747

4848
_cache = attr.ib()

0 commit comments

Comments
 (0)