Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python all() and bool() empty cases?

when using help(all), it returns:

all(iterable)=>bool
return True if bool(x) is True for all values x in the iterable.    
if the iterable is empty, return True

help(bool) returns:

bool(x) -> bool
 |  
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.

when trying:

>>>bool()
False

>>>all([])
True

my question is, in case that all's input is the empty list/dict/tuple(i.e. iterator), what's passed to bool?? and how come it returns True, as it's dependent on bool?

like image 809
moostahfah Avatar asked Nov 27 '22 13:11

moostahfah


1 Answers

bool() is never invoked if all()'s argument is empty. That's why the docs point out the behavior of all() on an empty input as a special case.

The behavior bool() == False is irrelevant to what all() does in any case. By the way, in Python bool is a subclass of int, so bool() == False is necessary to be compatible with that int() == 0.

As to why, e.g., all([]) is True, it's to preserve useful identities. Most importantly, for any non-empty sequence x it's desirable that

all(x) == (bool(x[0]) and all(x[1:]))

and all([]) == True is the only result allowing that identity to hold for all values of x.

like image 143
Tim Peters Avatar answered Dec 17 '22 10:12

Tim Peters