Page MenuHomeSoftware Heritage
Paste P1110

bad stream_results_optional

Authored by vlorentz on Jul 30 2021, 3:31 PM.
def stream_results_optional(
f: Callable[..., Optional[PagedResult[TResult, TToken]]], *args, **kwargs
) -> Optional[Iterable[TResult]]:
"""Like stream_results(), but for functions ``f`` that return an Optional.
if "page_token" in kwargs:
raise TypeError('stream_results has no argument "page_token".')
res = f(*args, page_token=None, **kwargs)
if res is None:
return None
return stream_results(f, *args, **kwargs)

Event Timeline

vlorentz updated the paste's language from autodetect to python.
vlorentz edited the content of this paste. (Show Details)

why not something like:

if res is None:
    return None
    yield res
    yield from stream_results(f, page_token = res.page_token, **kwargs)

(not sure about the page_token API here)

Because, if there is a single yield expression in the function's AST, Python parses the function as a generator, so it can only return generator objects None.

>>> def f():
...     if True:
...         return None
...     else:
...         yield 42
>>> f()
<generator object f at 0x7fc494dbc7c8>
>>> list(f())

ok then

return itertools.chain([res], stream_results(f, page_token = res.page_token, **kwargs))

(note sure it's really better, but...)