1

Does Python 3 implement short-circuiting in built-in functions whenever possible, just like it does for boolean statements?

A specific example, take the below code snippet:

min((20,11), key = lambda x : x % 10) # 20

Does Python evaluate beforehand that the minimum value possible of the function passed as the key argument is 0, and therefore stops right after evaluating the first integer in the iterable passed (20) as 20 % 10 is equal to 0? Or does it have to evaluate all the elements in the iterable before returning the answer?

I guess short-circuiting isn't even always possible especially for more complex functions, but what about for well-known, built-in functions or operators like %?

I couldn't find the answer in the official docs.

Thanks,

1

1 Answer 1

2

python has to evaluate all values inside the iterable because the languaje evaluate element by element, if you have in your tuple something that is not a number it will trigger an exception when try to perform the % operation. Python can not guess what is inside your list. You can test this by defining a function instead of a lambda and set debug point inside.

def my_mod(x): 
    import ipdb; ipdb.set_trace() 
    return x % 20 

then call the function

min((20,11), key = my_mod)

you can do a quick error test case with

min((20,11, "s"), key = my_mod)

It will trigger an exception but first had to evaluate all the previous element in the list.

Sign up to request clarification or add additional context in comments.

1 Comment

Min has to evaluate everything. OTOH any and all can short-circuit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.