Returning from a multiple stacked call at once

Chris Angelico rosuav at gmail.com
Tue Dec 15 06:25:58 EST 2020


On Tue, Dec 15, 2020 at 9:56 PM jak <nospam at please.ty> wrote:
>
> this could be a way to emulate a long_jump:
>
> def f(i):
>      if i < 10:
>          i += 1
>          yield from f(i)
>      else:
>          yield i
>
> i = 0
> retult = 0
> for n in f(i):
>      result = n
>      break
> print(result)
>

Note that this requires just as much cooperation as this version does:

def f(i):
    if i < 10:
        return f(i + 1)
    return i

result = f(0)

The only difference is that "yield from" sorta kinda gives you a
"maybe return", but you're not actually using that in your example, so
it doesn't showcase that. But let's say you're searching a complex
data structure for something:

def find(obj, pred):
    if pred(obj): yield obj
    if isinstance(obj, list):
        for elem in obj: yield from find(elem, pred)
    if isinstance(obj, dict):
        for elem in obj.values(): yield from find(elem, pred)

Taking the first matching element could be done without worrying too
much about whether any subsequent elements would match. I wouldn't
really call this a "long jump", though; this is a lazy filter that can
be efficiently used to locate the first few results without
calculating them all.

ChrisA


More information about the Python-list mailing list