| 1 |
from stripe._stripe_object import StripeObject |
| 2 |
from typing import List, Optional, TypeVar, Generic |
| 3 |
|
| 4 |
|
| 5 |
T = TypeVar("T", bound=StripeObject) |
| 6 |
|
| 7 |
|
| 8 |
class ListObject(StripeObject, Generic[T]): |
| 9 |
""" |
| 10 |
Represents one page of a list of V2 Stripe objects. Use `.data` to access |
| 11 |
the objects on this page, or use |
| 12 |
|
| 13 |
for item in list_object.auto_paging_iter(): |
| 14 |
# do something with item |
| 15 |
|
| 16 |
to iterate over this and all following pages. |
| 17 |
""" |
| 18 |
|
| 19 |
OBJECT_NAME = "list" |
| 20 |
data: List[T] |
| 21 |
next_page_url: Optional[str] |
| 22 |
|
| 23 |
def __getitem__(self, k): |
| 24 |
if isinstance(k, str): # type: ignore |
| 25 |
return super(ListObject, self).__getitem__(k) |
| 26 |
else: |
| 27 |
raise KeyError( |
| 28 |
"You tried to access the %s index, but ListObjectV2 types only " |
| 29 |
"support string keys. (HINT: List calls return an object with " |
| 30 |
"a 'data' (which is the data array). You likely want to call " |
| 31 |
".data[%s])" % (repr(k), repr(k)) |
| 32 |
) |
| 33 |
|
| 34 |
def __iter__(self): |
| 35 |
return getattr(self, "data", []).__iter__() |
| 36 |
|
| 37 |
def __len__(self): |
| 38 |
return getattr(self, "data", []).__len__() |
| 39 |
|
| 40 |
def __reversed__(self): |
| 41 |
return getattr(self, "data", []).__reversed__() |
| 42 |
|
| 43 |
def auto_paging_iter(self): |
| 44 |
page = self.data |
| 45 |
next_page_url = self.next_page_url |
| 46 |
while True: |
| 47 |
for item in page: |
| 48 |
yield item |
| 49 |
if next_page_url is None: |
| 50 |
break |
| 51 |
|
| 52 |
result = self._request( |
| 53 |
"get", |
| 54 |
next_page_url, |
| 55 |
base_address="api", |
| 56 |
) |
| 57 |
assert isinstance(result, ListObject) |
| 58 |
page = result.data |
| 59 |
next_page_url = result.next_page_url |