I'm confused about python's handing of objects during execution of all
. The documentation says that it is equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
From this trivial example, it seems like that is not the case:
class Foo:
def __init__(self, v):
self.v = v
a = Foo(5)
b = None
if a and b and a.v == b.v:
print("hello1")
else:
print("goodbye1")
if all([a, b, a.v == b.v]):
print("hello2")
else:
print("goodbye2")
This causes the all
line to crash with the error:
goodbye1
AttributeError: 'NoneType' object has no attribute 'v' Line 13 in (Solution.py)
I looks like the cpython implementation should prevent this failure, but it doesn't. What's going on here? Why does the same expression crash within all
, but works as expected when expanded?