Get the first item in a sequence that matches a condition I've been trying to figure out what's the best, most Pythonic way to get the first element of a sequence that matches a condition. Here are three options:

I don't like that I've written caller[0].f_locals.get(&quot;runner&quot;) twice, but it feels most Pythonic otherwise.
runner = next(
    caller[0].f_locals.get(&quot;runner&quot;)
    for caller in inspect.stack()
    if isinstance(caller[0].f_locals.get(&quot;runner&quot;), AbstractRunner)
)


Is it weird to rely on an assignment during the loop?
for caller in inspect.stack():
    runner = caller[0].f_locals.get(&quot;runner&quot;)
    if isinstance(runner, AbstractRunner):
        break


The second line is Pythonic and all, but the first line is only there to set up a generator where you no longer have to compute the expression (only apply the conditional in the second line).
generator = (caller[0].f_locals.get(&quot;runner&quot;) for caller in inspect.stack())
runner = next(x for x in generator if isinstance(x, AbstractRunner))



There's no performance difference at all from my tests.
This is a use case for the walrus operator :=, which was introduced in Python 3.8. It allows you to write 1) without repeating yourself:
runner = next(
    r
    for caller in inspect.stack()
    if isinstance(r := caller[0].f_locals.get(&quot;runner&quot;), AbstractRunner)
)

Whether or not you find this more readable or if this is too much nestedness in the if part is up to personal taste.