Skip to content

Commit c48da8d

Browse files
Copilotdkropachev
andcommitted
Optimize populate methods using defaultdict
- Use defaultdict(list) instead of manual dict initialization - Cleaner and more pythonic code - All tests still pass Co-authored-by: dkropachev <[email protected]>
1 parent 9a99da7 commit c48da8d

File tree

1 file changed

+5
-12
lines changed

1 file changed

+5
-12
lines changed

cassandra/policies.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414
import random
1515

16-
from collections import namedtuple
16+
from collections import namedtuple, defaultdict
1717
from functools import lru_cache
1818
from itertools import islice, cycle, groupby, repeat
1919
import logging
@@ -254,11 +254,9 @@ def _dc(self, host):
254254

255255
def populate(self, cluster, hosts):
256256
# Group hosts by datacenter without relying on groupby which only groups consecutive items
257-
dc_hosts_dict = {}
257+
dc_hosts_dict = defaultdict(list)
258258
for host in hosts:
259259
dc = self._dc(host)
260-
if dc not in dc_hosts_dict:
261-
dc_hosts_dict[dc] = []
262260
dc_hosts_dict[dc].append(host)
263261

264262
# Convert lists to tuples with unique hosts
@@ -383,22 +381,17 @@ def _dc(self, host):
383381

384382
def populate(self, cluster, hosts):
385383
# Group hosts by (dc, rack) and by dc without relying on groupby which only groups consecutive items
386-
rack_hosts_dict = {}
387-
dc_hosts_dict = {}
384+
rack_hosts_dict = defaultdict(list)
385+
dc_hosts_dict = defaultdict(list)
388386

389387
for host in hosts:
390388
dc = self._dc(host)
391389
rack = self._rack(host)
392390

393391
# Group by (dc, rack)
394-
key = (dc, rack)
395-
if key not in rack_hosts_dict:
396-
rack_hosts_dict[key] = []
397-
rack_hosts_dict[key].append(host)
392+
rack_hosts_dict[(dc, rack)].append(host)
398393

399394
# Group by dc
400-
if dc not in dc_hosts_dict:
401-
dc_hosts_dict[dc] = []
402395
dc_hosts_dict[dc].append(host)
403396

404397
# Convert lists to tuples with unique hosts

0 commit comments

Comments
 (0)