Debian Codegraph @

src/auth0/management/core/pagination.py

raw symbols SCIP
1 # This file was auto-generated by Fern from our API Definition.
2
3 from __future__ import annotations
4
5 from dataclasses import dataclass
6 from typing import AsyncIterator, Awaitable, Callable, Generic, Iterator, List, Optional, TypeVar
7
8 # Generic to represent the underlying type of the results within a page
9 T = TypeVar("T")
10 # Generic to represent the type of the API response
11 R = TypeVar("R")
12
13
14 # SDKs implement a Page ABC per-pagination request, the endpoint then returns a pager that wraps this type
15 # for example, an endpoint will return SyncPager[UserPage] where UserPage implements the Page ABC. ex:
16 #
17 # SyncPager<InnerListType>(
18 # has_next=response.list_metadata.after is not None,
19 # items=response.data,
20 # # This should be the outer function that returns the SyncPager again
21 # get_next=lambda: list(..., cursor: response.cursor) (or list(..., offset: offset + 1))
22 # )
23
24
25 @dataclass(frozen=True)
26 class SyncPager(Generic[T, R]):
27 get_next: Optional[Callable[[], Optional[SyncPager[T, R]]]]
28 has_next: bool
29 items: Optional[List[T]]
30 response: R
31
32 # Here we type ignore the iterator to avoid a mypy error
33 # caused by the type conflict with Pydanitc's __iter__ method
34 # brought in by extending the base model
35 def __iter__(self) -> Iterator[T]: # type: ignore[override]
36 for page in self.iter_pages():
37 if page.items is not None:
38 yield from page.items
39
40 def iter_pages(self) -> Iterator[SyncPager[T, R]]:
41 page: Optional[SyncPager[T, R]] = self
42 while page is not None:
43 yield page
44
45 if not page.has_next or page.get_next is None:
46 return
47
48 page = page.get_next()
49 if page is None or page.items is None or len(page.items) == 0:
50 return
51
52 def next_page(self) -> Optional[SyncPager[T, R]]:
53 return self.get_next() if self.get_next is not None else None
54
55
56 @dataclass(frozen=True)
57 class AsyncPager(Generic[T, R]):
58 get_next: Optional[Callable[[], Awaitable[Optional[AsyncPager[T, R]]]]]
59 has_next: bool
60 items: Optional[List[T]]
61 response: R
62
63 async def __aiter__(self) -> AsyncIterator[T]:
64 async for page in self.iter_pages():
65 if page.items is not None:
66 for item in page.items:
67 yield item
68
69 async def iter_pages(self) -> AsyncIterator[AsyncPager[T, R]]:
70 page: Optional[AsyncPager[T, R]] = self
71 while page is not None:
72 yield page
73
74 if not page.has_next or page.get_next is None:
75 return
76
77 page = await page.get_next()
78 if page is None or page.items is None or len(page.items) == 0:
79 return
80
81 async def next_page(self) -> Optional[AsyncPager[T, R]]:
82 return await self.get_next() if self.get_next is not None else None