Debian Codegraph @

src/globus_sdk/paging/base.py

raw
1 from __future__ import annotations
2
3 import abc
4 import functools
5 import inspect
6 import sys
7 import typing as t
8
9 from globus_sdk.response import GlobusHTTPResponse
10
11 if sys.version_info >= (3, 10):
12 from typing import ParamSpec
13 else:
14 from typing_extensions import ParamSpec
15
16 PageT = t.TypeVar("PageT", bound=GlobusHTTPResponse)
17 P = ParamSpec("P")
18 R = t.TypeVar("R", bound=GlobusHTTPResponse)
19 C = t.TypeVar("C", bound=t.Callable[..., GlobusHTTPResponse])
20
21
22 # stub for mypy
23 class _PaginatedFunc(t.Generic[PageT]):
24 _has_paginator: bool
25 _paginator_class: type[Paginator[PageT]]
26 _paginator_items_key: str | None
27 _paginator_params: dict[str, t.Any]
28
29
30 class Paginator(t.Iterable[PageT], metaclass=abc.ABCMeta):
31 """
32 Base class for all paginators.
33 This guarantees is that they have generator methods named ``pages`` and ``items``.
34
35 Iterating on a Paginator is equivalent to iterating on its ``pages``.
36
37 :param method: A bound method of an SDK client, used to generate a paginated variant
38 :param items_key: The key to use within pages of results to get an array of items
39 :param client_args: Arguments to the underlying method which are passed when the
40 paginator is instantiated. i.e. given ``client.paginated.foo(a, b, c=1)``, this
41 will be ``(a, b)``. The paginator will pass these arguments to each call of the
42 bound method as it pages.
43 :param client_kwargs: Keyword arguments to the underlying method, like
44 ``client_args`` above. ``client.paginated.foo(a, b, c=1)`` will pass this as
45 ``{"c": 1}``. As with ``client_args``, it's passed to each paginated call.
46 """
47
48 # the arguments which must be supported on the paginated method in order
49 # for the paginator to pass them
50 _REQUIRES_METHOD_KWARGS: tuple[str, ...] = ()
51
52 def __init__(
53 self,
54 method: t.Callable[..., t.Any],
55 *,
56 items_key: str | None = None,
57 client_args: tuple[t.Any, ...],
58 client_kwargs: dict[str, t.Any],
59 # the Base paginator must accept arbitrary additional kwargs to indicate that
60 # its child classes could define and use additional kwargs
61 **kwargs: t.Any,
62 ) -> None:
63 self.method = method
64 self.items_key = items_key
65 self.client_args = client_args
66 self.client_kwargs = client_kwargs
67
68 def __iter__(self) -> t.Iterator[PageT]:
69 yield from self.pages()
70
71 @abc.abstractmethod
72 def pages(self) -> t.Iterator[PageT]:
73 """``pages()`` yields GlobusHTTPResponse objects, each one representing a page
74 of results."""
75
76 def items(self) -> t.Iterator[t.Any]:
77 """
78 ``items()`` of a paginator is a generator which yields each item in each page of
79 results.
80
81 ``items()`` may raise a ``ValueError`` if the paginator was constructed without
82 identifying a key for use within each page of results. This may be the case for
83 paginators whose pages are not primarily an array of data.
84 """
85 if self.items_key is None:
86 raise ValueError(
87 "Cannot provide items() iteration on a paginator where 'items_key' "
88 "is not set."
89 )
90 for page in self.pages():
91 yield from page[self.items_key]
92
93 @classmethod
94 def wrap(cls, method: t.Callable[P, R]) -> t.Callable[P, Paginator[R]]:
95 """
96 This is an alternate method for getting a paginator for a paginated method which
97 correctly preserves the type signature of the paginated method.
98
99 It should be used on instances of clients and only passed bound methods of those
100 clients. For example, given usage
101
102 >>> tc = TransferClient()
103 >>> paginator = tc.paginated.endpoint_search(...)
104
105 a well-typed paginator can be acquired with
106
107 >>> tc = TransferClient()
108 >>> paginated_call = Paginator.wrap(tc.endpoint_search)
109 >>> paginator = paginated_call(...)
110
111 Although the syntax is slightly more verbose, this allows `mypy` and other type
112 checkers to more accurately infer the type of the paginator.
113
114 :param method: The method to convert to a paginator
115 """
116 if not inspect.ismethod(method):
117 raise TypeError(f"Paginator.wrap can only be used on methods, not {method}")
118 if not getattr(method, "_has_paginator", False):
119 raise ValueError(f"'{method}' is not a paginated method")
120
121 as_paginated = t.cast(_PaginatedFunc[PageT], method)
122 paginator_class = as_paginated._paginator_class
123 paginator_params = as_paginated._paginator_params
124 paginator_items_key = as_paginated._paginator_items_key
125
126 @functools.wraps(method)
127 def paginated_method(*args: t.Any, **kwargs: t.Any) -> Paginator[PageT]:
128 return paginator_class(
129 method,
130 client_args=tuple(args),
131 client_kwargs=kwargs,
132 items_key=paginator_items_key,
133 **paginator_params,
134 )
135
136 return t.cast(t.Callable[P, Paginator[R]], paginated_method)
137
138
139 def has_paginator(
140 paginator_class: type[Paginator[PageT]],
141 items_key: str | None = None,
142 **paginator_params: t.Any,
143 ) -> t.Callable[[C], C]:
144 """
145 Mark a callable -- typically a client method -- as having pagination parameters.
146 Usage:
147
148 >>> class MyClient(BaseClient):
149 >>> @has_paginator(MarkerPaginator)
150 >>> def foo(...): ...
151
152 This will mark ``MyClient.foo`` as paginated with marker style pagination.
153 It will then be possible to get a paginator for ``MyClient.foo`` via
154
155 >>> c = MyClient(...)
156 >>> paginator = c.paginated.foo()
157
158 :param paginator_class: The type of paginator used by this method
159 :param items_key: The key to use within pages of results to get an array of items
160 :param paginator_params: Additional parameters to pass to the paginator constructor
161 """
162
163 def decorate(func: C) -> C:
164 as_paginated = t.cast(_PaginatedFunc[PageT], func)
165 as_paginated._has_paginator = True
166 as_paginated._paginator_class = paginator_class
167 as_paginated._paginator_items_key = items_key
168 as_paginated._paginator_params = paginator_params
169 return func
170
171 return decorate