Skip to content

Commit 43e53a6

Browse files
committed
list to dict
1 parent 04ca439 commit 43e53a6

File tree

2 files changed

+10
-20
lines changed

2 files changed

+10
-20
lines changed

src/apify_client/_statistics.py

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from collections import defaultdict
12
from dataclasses import dataclass, field
23

34

@@ -11,7 +12,7 @@ class Statistics:
1112
requests: int = 0
1213
"""Total number of HTTP requests sent, including retries."""
1314

14-
rate_limit_errors: list[int] = field(default_factory=list)
15+
rate_limit_errors: defaultdict[int, int] = field(default_factory=lambda: defaultdict(int))
1516
"""List tracking which retry attempts encountered rate limit (429) errors."""
1617

1718
def add_rate_limit_error(self, attempt: int) -> None:
@@ -23,15 +24,4 @@ def add_rate_limit_error(self, attempt: int) -> None:
2324
if attempt < 1:
2425
raise ValueError('Attempt must be greater than 0')
2526

26-
index = attempt - 1
27-
self._ensure_list_capacity(index)
28-
self.rate_limit_errors[index] += 1
29-
30-
def _ensure_list_capacity(self, index: int) -> None:
31-
"""Ensure rate_limit_errors list has enough capacity.
32-
33-
Args:
34-
index: Required index to access
35-
"""
36-
if len(self.rate_limit_errors) <= index:
37-
self.rate_limit_errors.extend([0] * (index - len(self.rate_limit_errors) + 1))
27+
self.rate_limit_errors[attempt - 1] += 1

tests/unit/test_statistics.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
@pytest.mark.parametrize(
77
('attempts', 'expected_errors'),
88
[
9-
([1], [1]),
10-
([1, 5], [1, 0, 0, 0, 1]),
11-
([5, 1], [1, 0, 0, 0, 1]),
12-
([3, 5, 1], [1, 0, 1, 0, 1]),
13-
([1, 5, 3], [1, 0, 1, 0, 1]),
14-
([2, 1, 2, 1, 5, 2, 1], [3, 3, 0, 0, 1]),
9+
([1], {0: 1}),
10+
([1, 5], {0: 1, 4: 1}),
11+
([5, 1], {0: 1, 4: 1}),
12+
([3, 5, 1], {0: 1, 2: 1, 4: 1}),
13+
([1, 5, 3], {0: 1, 2: 1, 4: 1}),
14+
([2, 1, 2, 1, 5, 2, 1], {0: 3, 1: 3, 4: 1}),
1515
],
1616
ids=[
1717
'single_error',
@@ -42,7 +42,7 @@ def test_statistics_initial_state() -> None:
4242
stats = Statistics()
4343
assert stats.calls == 0
4444
assert stats.requests == 0
45-
assert stats.rate_limit_errors == []
45+
assert stats.rate_limit_errors == {}
4646

4747

4848
def test_add_rate_limit_error_type_validation() -> None:

0 commit comments

Comments
 (0)