Skip to content

Utils

General utilities package.

StreamYielder(*, skip_existing, filter_fn, unique_key_fn, limit, min_wait_time, max_wait_time)

Helper class to manage a stream and keep track of previously seen results.

Initialize StreamYielder.

Parameters:

  • unique_key_fn (Callable[[T], str]) –

    A function that takes an object and outputs a unique id. This is used to keep track of what results were already yielded.

  • filter_fn (Callable[[T], bool]) –

    Ignore objects which return True for this function.

  • limit (Optional[int]) –

    Maximum number of objects to yield.

  • max_wait_time (int) –

    If a function returns no new results, the time between calls to it increases. This sets the maximum time (in seconds) to wait before calling it again.

  • min_wait_time (int) –

    Minimum time (in seconds) to wait before calling the function again.

  • skip_existing (bool) –

    If True, skip existing results and return only future ones. In practice, this means the results from the first request are ignored.

Source code in pylemmy/utils.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def __init__(
    self,
    *,
    skip_existing: bool,
    filter_fn: Callable[[T], bool],
    unique_key_fn: Callable[[T], str],
    limit: Optional[int],
    min_wait_time: int,
    max_wait_time: int,
):
    """Initialize StreamYielder.

    :param unique_key_fn: A function that takes an object and outputs a unique id.
    This is used to keep track of what results were already yielded.
    :param filter_fn: Ignore objects which return `True` for this function.
    :param limit: Maximum number of objects to yield.
    :param max_wait_time: If a function returns no new results, the time between
    calls to it increases. This sets the maximum time (in seconds) to wait before
    calling it again.
    :param min_wait_time: Minimum time (in seconds) to wait before calling the
    function again.
    :param skip_existing: If `True`, skip existing results and return only future
    ones.
    In practice, this means the results from the first request are ignored.
    """
    self.skip_existing = skip_existing
    self.filter_fn = filter_fn
    self.unique_key_fn = unique_key_fn
    self.limit = limit

    self.results_count = 0
    self.requests_count = 0
    self.found_keys: Set[str] = set()
    self.last_seen_key = ""

    self.wait_time = min_wait_time
    self.min_wait_time = min_wait_time
    self.max_wait_time = max_wait_time

get_wait_time(first_key)

Get how long we should wait.

Parameters:

  • first_key (str) –

    First key seen in the previous iteration. If this is the same as self.last_seen_key it means that no new content was seen in the last request, and so wait time should increase.

Source code in pylemmy/utils.py
84
85
86
87
88
89
90
91
92
93
94
95
def get_wait_time(self, first_key: str) -> int:
    """Get how long we should wait.

    :param first_key: First key seen in the previous iteration.
    If this is the same as `self.last_seen_key` it means that no new content
    was seen in the last request, and so wait time should increase.
    """
    if first_key == self.last_seen_key:  # no new results
        self.wait_time = min(2 * self.wait_time, self.max_wait_time)
    else:
        self.wait_time = self.min_wait_time
    return self.wait_time

yield_results(results)

Iterate through the results.

Parameters:

  • results (Iterable[T]) –

    Results from one to the generator function.

Source code in pylemmy/utils.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def yield_results(self, results: Iterable[T]) -> Generator[Optional[T], None, None]:
    """Iterate through the results.

    :param results: Results from one to the generator function.
    """
    skipping_yield = False
    if self.requests_count == 1 and self.skip_existing:
        skipping_yield = True
    for r in filter(self.filter_fn, results):  # type: ignore[var-annotated, arg-type]
        unique_key = self.unique_key_fn(r)
        if unique_key not in self.found_keys:
            self.last_seen_key = unique_key
            if not skipping_yield:
                yield r
                self.results_count += 1
            if self.limit is not None and self.results_count >= self.limit:
                yield None
            self.found_keys.add(unique_key)

async_stream_generator(results_fn, unique_key_fn, *, filter_fn=lambda _: True, limit=None, max_wait_time=300, min_wait_time=1, skip_existing=False, **function_kwargs) async

Helper function to generate streams.

Parameters:

  • results_fn (Callable[[KwArg(Any)], Iterable[T]]) –

    A function to call repeatedly, which outputs a list of objects.

  • unique_key_fn (Callable[[T], str]) –

    A function that takes an object and outputs a unique id. This is used to keep track of what results were already yielded.

  • filter_fn (Callable[[T], bool], default: lambda _: True ) –

    Ignore objects which return True for this function.

  • limit (Optional[int], default: None ) –

    Maximum number of objects to yield.

  • max_wait_time (int, default: 300 ) –

    If a function returns no new results, the time between calls to it increases. This sets the maximum time (in seconds) to wait before calling it again.

  • min_wait_time (int, default: 1 ) –

    Minimum time (in seconds) to wait before calling the function again.

  • skip_existing (bool, default: False ) –

    If True, skip existing results and return only future ones. In practice, this means the results from the first request are ignored.

  • function_kwargs (Any, default: {} ) –

    Keyword parameters that are passed to the function.

Source code in pylemmy/utils.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
async def async_stream_generator(
    results_fn: Callable[[KwArg(Any)], Iterable[T]],
    unique_key_fn: Callable[[T], str],
    *,
    filter_fn: Callable[[T], bool] = lambda _: True,
    limit: Optional[int] = None,
    max_wait_time: int = 300,
    min_wait_time: int = 1,
    skip_existing: bool = False,
    **function_kwargs: Any,
) -> AsyncGenerator[T, None]:
    """Helper function to generate streams.

    :param results_fn: A function to call repeatedly, which outputs a list of objects.
    :param unique_key_fn: A function that takes an object and outputs a unique id.
    This is used to keep track of what results were already yielded.
    :param filter_fn: Ignore objects which return `True` for this function.
    :param limit: Maximum number of objects to yield.
    :param max_wait_time: If a function returns no new results, the time between calls
    to it increases. This sets the maximum time (in seconds) to wait before calling it
    again.
    :param min_wait_time: Minimum time (in seconds) to wait before calling the function
    again.
    :param skip_existing: If `True`, skip existing results and return only future ones.
    In practice, this means the results from the first request are ignored.
    :param function_kwargs: Keyword parameters that are passed to the function.
    """
    stream_obj = StreamYielder(
        skip_existing=skip_existing,
        filter_fn=filter_fn,
        unique_key_fn=unique_key_fn,
        limit=limit,
        min_wait_time=min_wait_time,
        max_wait_time=max_wait_time,
    )
    while True:
        first_key = stream_obj.last_seen_key
        results = results_fn(**function_kwargs)
        for r in stream_obj.yield_results(results):
            if r is None:
                return
            yield r

        await asyncio.sleep(stream_obj.get_wait_time(first_key))

stream_apply(results_fns, unique_key_fns, callback, *, filter_fn=lambda _: True, limit=None, max_wait_time=300, min_wait_time=1, **function_kwargs)

Helper function to generate streams.

Parameters:

  • results_fns (Sequence[Callable[[KwArg(Any)], Iterable[T]]]) –

    A list of functions to call repeatedly, each of them outputting a list of objects.

  • unique_key_fns (Sequence[Callable[[T], str]]) –

    A list of functions (same length as function), where each of them takes an object and outputs a unique id. This is used to keep track of what results were already yielded.

  • callback (Callable[[T], Any]) –

    A function that is applied to each of the objects.

  • filter_fn (Callable[[T], bool], default: lambda _: True ) –

    Ignore objects which return True for this function.

  • limit (Optional[int], default: None ) –

    Maximum number of objects to yield.

  • max_wait_time (int, default: 300 ) –

    If a function returns no new results, the time between calls to it increases. This sets the maximum time (in seconds) to wait before calling it again.

  • min_wait_time (int, default: 1 ) –

    Minimum time (in seconds) to wait before calling the function again.

  • function_kwargs (Any, default: {} ) –

    Keyword parameters that are passed to the function.

Source code in pylemmy/utils.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def stream_apply(
    results_fns: Sequence[Callable[[KwArg(Any)], Iterable[T]]],
    unique_key_fns: Sequence[Callable[[T], str]],
    callback: Callable[[T], Any],
    *,
    filter_fn: Callable[[T], bool] = lambda _: True,
    limit: Optional[int] = None,
    max_wait_time: int = 300,
    min_wait_time: int = 1,
    **function_kwargs: Any,
):
    """Helper function to generate streams.

    :param results_fns: A list of functions to call repeatedly, each of them
    outputting a list of objects.
    :param unique_key_fns: A list of functions (same length as `function`), where
    each of them takes an object and outputs a unique id.
    This is used to keep track of what results were already yielded.
    :param callback: A function that is applied to each of the objects.
    :param filter_fn: Ignore objects which return `True` for this function.
    :param limit: Maximum number of objects to yield.
    :param max_wait_time: If a function returns no new results, the time between calls
    to it increases. This sets the maximum time (in seconds) to wait before calling it
    again.
    :param min_wait_time: Minimum time (in seconds) to wait before calling the function
    again.
    :param function_kwargs: Keyword parameters that are passed to the function.
    """
    if len(results_fns) != len(unique_key_fns):
        msg = (
            f"The lengths of `generator_fns` and `unique_key_fns` need to be the same. "
            f"Got {len(results_fns)} and {len(unique_key_fns)}."
        )
        raise ValueError(msg)
    asyncio.run(
        _merge_streams(
            results_fns,
            unique_key_fns,
            callback,
            filter_fn=filter_fn,
            limit=limit,
            max_wait_time=max_wait_time,
            min_wait_time=min_wait_time,
            **function_kwargs,
        )
    )

stream_generator(results_fn, unique_key_fn, *, filter_fn=lambda _: True, limit=None, max_wait_time=300, min_wait_time=1, skip_existing=False, **function_kwargs)

Helper function to generate streams.

Parameters:

  • results_fn (Callable[[KwArg(Any)], Iterable[T]]) –

    A function to call repeatedly, which outputs a list of objects.

  • unique_key_fn (Callable[[T], str]) –

    A function that takes an object and outputs a unique id. This is used to keep track of what results were already yielded.

  • filter_fn (Callable[[T], bool], default: lambda _: True ) –

    Ignore objects which return True for this function.

  • limit (Optional[int], default: None ) –

    Maximum number of objects to yield.

  • max_wait_time (int, default: 300 ) –

    If a function returns no new results, the time between calls to it increases. This sets the maximum time (in seconds) to wait before calling it again.

  • min_wait_time (int, default: 1 ) –

    Minimum time (in seconds) to wait before calling the function again.

  • skip_existing (bool, default: False ) –

    If True, skip existing results and return only future ones. In practice, this means the results from the first request are ignored.

  • function_kwargs (Any, default: {} ) –

    Keyword parameters that are passed to the function.

Source code in pylemmy/utils.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def stream_generator(
    results_fn: Callable[[KwArg(Any)], Iterable[T]],
    unique_key_fn: Callable[[T], str],
    *,
    filter_fn: Callable[[T], bool] = lambda _: True,
    limit: Optional[int] = None,
    max_wait_time: int = 300,
    min_wait_time: int = 1,
    skip_existing: bool = False,
    **function_kwargs: Any,
) -> Generator[T, None, None]:
    """Helper function to generate streams.

    :param results_fn: A function to call repeatedly, which outputs a list of objects.
    :param unique_key_fn: A function that takes an object and outputs a unique id.
    This is used to keep track of what results were already yielded.
    :param filter_fn: Ignore objects which return `True` for this function.
    :param limit: Maximum number of objects to yield.
    :param max_wait_time: If a function returns no new results, the time between calls
    to it increases. This sets the maximum time (in seconds) to wait before calling it
    again.
    :param min_wait_time: Minimum time (in seconds) to wait before calling the function
    again.
    :param skip_existing: If `True`, skip existing results and return only future ones.
    In practice, this means the results from the first request are ignored.
    :param function_kwargs: Keyword parameters that are passed to the function.
    """
    stream_obj = StreamYielder(
        skip_existing=skip_existing,
        filter_fn=filter_fn,
        unique_key_fn=unique_key_fn,
        limit=limit,
        min_wait_time=min_wait_time,
        max_wait_time=max_wait_time,
    )
    while True:
        first_key = stream_obj.last_seen_key
        results = results_fn(**function_kwargs)
        for r in stream_obj.yield_results(results):
            if r is None:
                return
            yield r

        time.sleep(stream_obj.get_wait_time(first_key))