Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't all() stop on the first False element?

Tags:

python

From the docs, all is equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

Then why do I get this output:

# expecting: False

$ python -c "print( all( (isinstance('foo', int), int('foo')) ) )"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

When:

# expecting: False

$ python -c "print( isinstance('foo', int) )"
False
like image 941
Jace Browning Avatar asked Dec 07 '22 06:12

Jace Browning


1 Answers

One (fairly ugly) way to get the behaviour you want is via lambdas:

all(f() for f in (lambda: isinstance('foo', int), lambda: int('foo')))
like image 191
Daniel Roseman Avatar answered Dec 21 '22 18:12

Daniel Roseman