Skip to content

Commit 366dfb1

Browse files
committed
Refactor BasePaginatedResponse getitem slightly
and add an exhaustive docstring.
1 parent 3555afc commit 366dfb1

1 file changed

Lines changed: 24 additions & 22 deletions

File tree

discogs_client/models.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -354,39 +354,41 @@ def _transform(self, item):
354354
return item
355355

356356
def __getitem__(self, index):
357+
"""Retrieve an item by its index.
358+
359+
By default, uses the API's ``per_page`` value to calculate the page
360+
containing the item directly. If the API returns fewer items per page
361+
than reported, this may yield incorrect results — set
362+
``client.trust_per_page = False`` to fall back to a sequential page
363+
walk at the cost of performance.
364+
"""
357365
if self.client._trust_per_page:
358-
# Directly jump to index using offset math.
359-
# Default
360366
page_index = index // self.per_page + 1
361367
offset = index % self.per_page
362368

363369
try:
364370
page = self.page(page_index)
365371
except HTTPError as e:
366372
if e.status_code == 404:
367-
raise IndexError(e.msg)
368-
else:
369-
raise
373+
raise IndexError(e.msg) from e
374+
raise
370375

371376
return page[offset]
372377

373-
else:
374-
# Sequentially walks through each page until index or end of array reached.
375-
# Opt-in
376-
current = 0
377-
page_index = 1
378-
while True:
379-
try:
380-
page = self.page(page_index)
381-
except HTTPError as e:
382-
if e.status_code == 404:
383-
raise IndexError(e.msg)
384-
else:
385-
raise
386-
if current + len(page) > index:
387-
return page[index - current]
388-
current += len(page)
389-
page_index += 1
378+
# Fallback to sequential page loading if we're not trusting the per_page parameter
379+
current = 0
380+
page_index = 1
381+
while True:
382+
try:
383+
page = self.page(page_index)
384+
except HTTPError as e:
385+
if e.status_code == 404:
386+
raise IndexError(e.msg) from e
387+
raise
388+
if current + len(page) > index:
389+
return page[index - current]
390+
current += len(page)
391+
page_index += 1
390392

391393

392394
def __len__(self):

0 commit comments

Comments
 (0)