简体   繁体   中英

Evaluation of function in python list comprehension action step and condition at the same time

I am interested in what does python under the hood in the following code.

def test_func(a: str) -> str or None:
    # Just example
    if a.endswith("r"):
        return f"{a}rr"
    elif a.endswith("s"):
        return None
    else:
        return a

if __name__=="__main__":
    ...
    source_list = ["Edgar", "Pedros", "Alexander"]
    test = [test_func(x) for x in source_list if test_func(x)]

My question here is how python under the hood copes with the evaluation of the test_func(x) function. Is it done twice or python is able to recognize that the same result can be used on both places and evaluates the function only once? :-)

It calls test_func(x) twice for elements for which its truth value is true (and once for those whose truth value is false). If you only want to call it once in all cases, you can do:

test = [v for v in (test_func(x) for x in source_list) if v]

unless you store function results, as soon as you write a function name with pair of parenthesis new call to the function occur

Hah, so I just add there a print statement to the function and it has revealed itself.

The answer is that in case the condition is evaluated as positive the function is evaluated twice. Here is my example:

>>> def test(a: str) -> str or None:
...     print(f"HERE {a}")
...     if a.endswith("r"):
...         return f"{a}rr"
...     elif a.endswith("s"):
...         return None
...     else:
...         return a
...
>>> source = ["Edgar", "Pedros", "Alexander"]
>>> [test(x) for x in source if test(x)]
HERE Edgar
HERE Edgar
HERE Pedros
HERE Alexander
HERE Alexander

If you're using Python 3.8+, you can use the walrus operator which is perfect for this!

test = [tested for x in source_list if (tested := test_func(x))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM