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

Consistently use six's iteritems and wrap lazy keys/values in list() if they're not meant to be lazy #3307

Merged
merged 4 commits into from
May 31, 2018
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
4 changes: 3 additions & 1 deletion synapse/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

import logging

from six import itervalues

import pymacaroons
from twisted.internet import defer

Expand Down Expand Up @@ -66,7 +68,7 @@ def check_from_context(self, event, context, do_sig_check=True):
)
auth_events = yield self.store.get_events(auth_events_ids)
auth_events = {
(e.type, e.state_key): e for e in auth_events.values()
(e.type, e.state_key): e for e in itervalues(auth_events)
}
self.check(event, auth_events=auth_events, do_sig_check=do_sig_check)

Expand Down
2 changes: 1 addition & 1 deletion synapse/api/filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ def filter_rooms(self, room_ids):
return room_ids

def filter(self, events):
return filter(self.check, events)
return list(filter(self.check, events))

def limit(self):
return self.filter_json.get("limit", 10)
Expand Down
4 changes: 2 additions & 2 deletions synapse/event_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,14 +471,14 @@ def _check_power_levels(event, auth_events):
]

old_list = current_state.content.get("users", {})
for user in set(old_list.keys() + user_list.keys()):
for user in set(list(old_list) + list(user_list)):
levels_to_check.append(
(user, "users")
)

old_list = current_state.content.get("events", {})
new_list = event.content.get("events", {})
for ev_id in set(old_list.keys() + new_list.keys()):
for ev_id in set(list(old_list) + list(new_list)):
levels_to_check.append(
(ev_id, "events")
)
Expand Down
2 changes: 1 addition & 1 deletion synapse/events/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def __contains__(self, field):
return field in self._event_dict

def items(self):
return self._event_dict.items()
return list(self._event_dict.items())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it be nicer to do list(iteritems(...))?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's about twice as slow on Python 2, unfortunately:

~ $ python3 -m timeit "list(globals().items())"
1000000 loops, best of 3: 0.75 usec per loop
~ $ python -m timeit "list(globals().items())"
1000000 loops, best of 3: 0.67 usec per loop
~ $ python -m timeit "list(globals().iteritems())"
1000000 loops, best of 3: 1.02 usec per loop

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well that's fun :/



class FrozenEvent(EventBase):
Expand Down
4 changes: 2 additions & 2 deletions synapse/federation/federation_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ def get_events(self, destinations, room_id, event_ids, return_local=True):
"""
if return_local:
seen_events = yield self.store.get_events(event_ids, allow_rejected=True)
signed_events = seen_events.values()
signed_events = list(seen_events.values())
else:
seen_events = yield self.store.have_seen_events(event_ids)
signed_events = []
Expand Down Expand Up @@ -589,7 +589,7 @@ def send_join(self, destinations, pdu):
}

valid_pdus = yield self._check_sigs_and_hash_and_fetch(
destination, pdus.values(),
destination, list(pdus.values()),
outlier=True,
)

Expand Down
2 changes: 1 addition & 1 deletion synapse/federation/send_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def send_presence(self, states):

# We only want to send presence for our own users, so lets always just
# filter here just in case.
local_states = filter(lambda s: self.is_mine_id(s.user_id), states)
local_states = list(filter(lambda s: self.is_mine_id(s.user_id), states))

self.presence_map.update({state.user_id: state for state in local_states})
self.presence_changed[pos] = [state.user_id for state in local_states]
Expand Down
6 changes: 4 additions & 2 deletions synapse/federation/transaction_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@

from prometheus_client import Counter

from six import itervalues

import logging


Expand Down Expand Up @@ -234,7 +236,7 @@ def handle_room_events(events):
yield logcontext.make_deferred_yieldable(defer.gatherResults(
[
logcontext.run_in_background(handle_room_events, evs)
for evs in events_by_room.itervalues()
for evs in itervalues(events_by_room)
],
consumeErrors=True
))
Expand Down Expand Up @@ -325,7 +327,7 @@ def send_presence(self, states):
if not states_map:
break

yield self._process_presence_inner(states_map.values())
yield self._process_presence_inner(list(states_map.values()))
except Exception:
logger.exception("Error sending presence states to servers")
finally:
Expand Down
4 changes: 2 additions & 2 deletions synapse/handlers/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,14 +114,14 @@ def maybe_kick_guest_users(self, event, context=None):
if guest_access != "can_join":
if context:
current_state = yield self.store.get_events(
context.current_state_ids.values()
list(context.current_state_ids.values())
)
else:
current_state = yield self.state_handler.get_current_state(
event.room_id
)

current_state = current_state.values()
current_state = list(current_state.values())

logger.info("maybe_kick_guest_users %r", current_state)
yield self.kick_guest_users(current_state)
Expand Down
4 changes: 3 additions & 1 deletion synapse/handlers/appservice.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

from twisted.internet import defer

from six import itervalues

import synapse
from synapse.api.constants import EventTypes
from synapse.util.metrics import Measure
Expand Down Expand Up @@ -119,7 +121,7 @@ def handle_room_events(events):

yield make_deferred_yieldable(defer.gatherResults([
run_in_background(handle_room_events, evs)
for evs in events_by_room.itervalues()
for evs in itervalues(events_by_room)
], consumeErrors=True))

yield self.store.set_appservice_last_pos(upper_bound)
Expand Down
6 changes: 3 additions & 3 deletions synapse/handlers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,20 +249,20 @@ def check_auth(self, flows, clientdict, clientip):
errordict = e.error_dict()

for f in flows:
if len(set(f) - set(creds.keys())) == 0:
if len(set(f) - set(creds)) == 0:
# it's very useful to know what args are stored, but this can
# include the password in the case of registering, so only log
# the keys (confusingly, clientdict may contain a password
# param, creds is just what the user authed as for UI auth
# and is not sensitive).
logger.info(
"Auth completed with creds: %r. Client dict has keys: %r",
creds, clientdict.keys()
creds, list(clientdict)
)
defer.returnValue((creds, clientdict, session['id']))

ret = self._auth_dict_for_flows(flows, session)
ret['completed'] = creds.keys()
ret['completed'] = list(creds)
ret.update(errordict)
raise InteractiveAuthIncompleteError(
ret,
Expand Down
4 changes: 2 additions & 2 deletions synapse/handlers/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def get_devices_by_user(self, user_id):
user_id, device_id=None
)

devices = device_map.values()
devices = list(device_map.values())
for device in devices:
_update_device_from_client_ips(device, ips)

Expand Down Expand Up @@ -187,7 +187,7 @@ def delete_all_devices_for_user(self, user_id, except_device_id=None):
defer.Deferred:
"""
device_map = yield self.store.get_devices_by_user(user_id)
device_ids = device_map.keys()
device_ids = list(device_map)
if except_device_id is not None:
device_ids = [d for d in device_ids if d != except_device_id]
yield self.delete_devices(user_id, device_ids)
Expand Down
17 changes: 8 additions & 9 deletions synapse/handlers/federation.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@

from synapse.util.distributor import user_joined_room


logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -480,8 +479,8 @@ def check_match(id):
# to get all state ids that we're interested in.
event_map = yield self.store.get_events([
e_id
for key_to_eid in event_to_state_ids.itervalues()
for key, e_id in key_to_eid.iteritems()
for key_to_eid in list(event_to_state_ids.values())
for key, e_id in key_to_eid.items()
if key[0] != EventTypes.Member or check_match(key[1])
])

Expand Down Expand Up @@ -1149,13 +1148,13 @@ def on_send_join_request(self, origin, pdu):
user = UserID.from_string(event.state_key)
yield user_joined_room(self.distributor, user, event.room_id)

state_ids = context.prev_state_ids.values()
state_ids = list(context.prev_state_ids.values())
auth_chain = yield self.store.get_auth_chain(state_ids)

state = yield self.store.get_events(context.prev_state_ids.values())
state = yield self.store.get_events(list(context.prev_state_ids.values()))

defer.returnValue({
"state": state.values(),
"state": list(state.values()),
"auth_chain": auth_chain,
})

Expand Down Expand Up @@ -1405,7 +1404,7 @@ def get_state_for_pdu(self, room_id, event_id):
else:
del results[(event.type, event.state_key)]

res = results.values()
res = list(results.values())
for event in res:
# We sign these again because there was a bug where we
# incorrectly signed things the first time round
Expand Down Expand Up @@ -1446,7 +1445,7 @@ def get_state_ids_for_pdu(self, room_id, event_id):
else:
results.pop((event.type, event.state_key), None)

defer.returnValue(results.values())
defer.returnValue(list(results.values()))
else:
defer.returnValue([])

Expand Down Expand Up @@ -1915,7 +1914,7 @@ def do_auth(self, origin, event, context, auth_events):
})

new_state = self.state_handler.resolve_events(
[local_view.values(), remote_view.values()],
[list(local_view.values()), list(remote_view.values())],
event
)

Expand Down
12 changes: 6 additions & 6 deletions synapse/handlers/presence.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ def _update_states(self, new_states):

if to_notify:
notified_presence_counter.inc(len(to_notify))
yield self._persist_and_notify(to_notify.values())
yield self._persist_and_notify(list(to_notify.values()))

self.unpersisted_users_changes |= set(s.user_id for s in new_states)
self.unpersisted_users_changes -= set(to_notify.keys())
Expand Down Expand Up @@ -687,7 +687,7 @@ def get_states(self, target_user_ids, as_event=False):
"""

updates = yield self.current_state_for_users(target_user_ids)
updates = updates.values()
updates = list(updates.values())

for user_id in set(target_user_ids) - set(u.user_id for u in updates):
updates.append(UserPresenceState.default(user_id))
Expand Down Expand Up @@ -753,11 +753,11 @@ def user_joined_room(self, user, room_id):
self._push_to_remotes([state])
else:
user_ids = yield self.store.get_users_in_room(room_id)
user_ids = filter(self.is_mine_id, user_ids)
user_ids = list(filter(self.is_mine_id, user_ids))

states = yield self.current_state_for_users(user_ids)

self._push_to_remotes(states.values())
self._push_to_remotes(list(states.values()))

@defer.inlineCallbacks
def get_presence_list(self, observer_user, accepted=None):
Expand Down Expand Up @@ -1051,7 +1051,7 @@ def get_new_events(self, user, from_key, room_ids=None, include_offline=True,
updates = yield presence.current_state_for_users(user_ids_changed)

if include_offline:
defer.returnValue((updates.values(), max_token))
defer.returnValue((list(updates.values()), max_token))
else:
defer.returnValue(([
s for s in itervalues(updates)
Expand Down Expand Up @@ -1112,7 +1112,7 @@ def handle_timeouts(user_states, is_mine_fn, syncing_user_ids, now):
if new_state:
changes[state.user_id] = new_state

return changes.values()
return list(changes.values())


def handle_timeout(state, is_mine, syncing_user_ids, now):
Expand Down
2 changes: 1 addition & 1 deletion synapse/handlers/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ def filter_evts(events):
state = yield self.store.get_state_for_events(
[last_event_id], None
)
results["state"] = state[last_event_id].values()
results["state"] = list(state[last_event_id].values())

results["start"] = now_token.copy_and_replace(
"room_key", results["start"]
Expand Down
3 changes: 2 additions & 1 deletion synapse/handlers/room_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from twisted.internet import defer

from six import iteritems
from six.moves import range

from ._base import BaseHandler
Expand Down Expand Up @@ -307,7 +308,7 @@ def generate_room_entry(self, room_id, num_joined_users, cache_context,
)

event_map = yield self.store.get_events([
event_id for key, event_id in current_state_ids.iteritems()
event_id for key, event_id in iteritems(current_state_ids)
if key[0] in (
EventTypes.JoinRules,
EventTypes.Name,
Expand Down
2 changes: 1 addition & 1 deletion synapse/handlers/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ def search(self, user, content, batch=None):
rooms = set(e.room_id for e in allowed_events)
for room_id in rooms:
state = yield self.state_handler.get_current_state(room_id)
state_results[room_id] = state.values()
state_results[room_id] = list(state.values())

state_results.values()

Expand Down
6 changes: 3 additions & 3 deletions synapse/handlers/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,11 +541,11 @@ def compute_state_delta(self, room_id, batch, sync_config, since_token, now_toke

state = {}
if state_ids:
state = yield self.store.get_events(state_ids.values())
state = yield self.store.get_events(list(state_ids.values()))

defer.returnValue({
(e.type, e.state_key): e
for e in sync_config.filter_collection.filter_room_state(state.values())
for e in sync_config.filter_collection.filter_room_state(list(state.values()))
})

@defer.inlineCallbacks
Expand Down Expand Up @@ -894,7 +894,7 @@ def _generate_sync_entry_for_presence(self, sync_result_builder, newly_joined_ro
presence.extend(states)

# Deduplicate the presence entries so that there's at most one per user
presence = {p.user_id: p for p in presence}.values()
presence = list({p.user_id: p for p in presence}.values())

presence = sync_config.filter_collection.filter_presence(
presence
Expand Down
2 changes: 1 addition & 1 deletion synapse/push/baserules.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def list_with_base_rules(rawrules):
rawrules = [r for r in rawrules if r['priority_class'] >= 0]

# shove the server default rules for each kind onto the end of each
current_prio_class = PRIORITY_CLASS_INVERSE_MAP.keys()[-1]
current_prio_class = list(PRIORITY_CLASS_INVERSE_MAP)[-1]

ruleslist.extend(make_base_prepend_rules(
PRIORITY_CLASS_INVERSE_MAP[current_prio_class], modified_base_rules
Expand Down
3 changes: 2 additions & 1 deletion synapse/push/mailer.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,8 @@ def get_room_vars(self, room_id, user_id, notifs, notif_events, room_state_ids):
if room_vars['notifs'] and 'messages' in room_vars['notifs'][-1]:
prev_messages = room_vars['notifs'][-1]['messages']
for message in notifvars['messages']:
pm = filter(lambda pm: pm['id'] == message['id'], prev_messages)
pm = list(filter(lambda pm: pm['id'] == message['id'],
prev_messages))
if pm:
if not message["is_historical"]:
pm[0]["is_historical"] = False
Expand Down
2 changes: 1 addition & 1 deletion synapse/push/presentable_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def calculate_room_name(store, room_state_ids, user_id, fallback_to_members=True
# so find out who is in the room that isn't the user.
if "m.room.member" in room_state_bytype_ids:
member_events = yield store.get_events(
room_state_bytype_ids["m.room.member"].values()
list(room_state_bytype_ids["m.room.member"].values())
)
all_members = [
ev for ev in member_events.values()
Expand Down
2 changes: 1 addition & 1 deletion synapse/rest/client/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def remove_from_map(err):

def _cleanup(self):
now = self.clock.time_msec()
for key in self.transactions.keys():
for key in list(self.transactions):
ts = self.transactions[key][1]
if now > (ts + CLEANUP_PERIOD_MS): # after cleanup period
del self.transactions[key]
Loading