I've got two classes I'm testing to learn about how to use any() and all() with my own classes. Basically I have a class called Wrapped that has a member "self.members" which is a python list of class instances of another class called Unit. I've set up Unit so it defines a function called __bool__(self) like this:

The "print foo" shows what I expect via the __str__() in my Wrapped class :

Quote:

Unit() 3 Unit() None Unit() 12

But the "print "all: " + str(all(foo.members))" comes up unexpectedly:

Quote:

all: True

I would have expected all(foo.members) to be False since that 2nd class had a None for the "a", plus I also see that the all() doesn't seem to call the Unit.__bool__() anyway because my test "print" doesn't show. I was thinking the all() function always has to use __bool__ from the class in the list?

You cannot overload the bool() function in Python 2. The __bool__ special method is a Python 3 feature. In Python 2 it is nothing special hence useless in your code, which is why it's never called.

To run your code either use python3 (and you must modify your program to deal with the new grammar, in particular the print() function. The 2to3 tool can help you in this regard), or use the __nonzero__ special method.

You cannot overload the bool() function in Python 2. The __bool__ special method is a Python 3 feature. In Python 2 it is nothing special hence useless in your code, which is why it's never called.

To run your code either use python3 (and you must modify your program to deal with the new grammar, in particular the print() function. The 2to3 tool can help you in this regard), or use the __nonzero__ special method.

Wow, so in python 2.x you can't use all() or any() with user defined class lists but only lists using official python objects? It's possible the book I'm using has enough Python 3.x info in it I got mixed up

Wow, so in python 2.x you can't use all() or any() with user defined class lists but only lists using official python objects? It's possible the book I'm using has enough Python 3.x info in it I got mixed up

You just have to use __nonzero__ instead of __bool__ in Python 2. After you make this change, all() and any() should work as expected.