Book Image

Mastering Object-oriented Python

By : Steven F. Lott, Steven F. Lott
Book Image

Mastering Object-oriented Python

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (26 chapters)
Mastering Object-oriented Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Some Preliminaries
Index

The __bool__() method


Python has a pleasant definition of falsity. The reference manual lists a large number of values that will test as equivalent to False. This includes things such as False, 0, '', (), [], and {}. Most other objects will test as equivalent to True.

Often, we'll want to check for an object being "not empty" with a simple statement as follows:

if some_object:
    process( some_object )

Under the hood, this is the job of the bool() built-in function. This function depends on the __bool__() method of a given object.

The default __bool__() method returns True. We can see this with the following code:

>>> x = object()
>>> bool(x)
True

For most classes, this is perfectly valid. Most objects are not expected to be False. For collections, however, this is not appropriate. An empty collection should be equivalent to False. A nonempty collection can return True. We might want to add a method like this to our Deck objects.

If we're wrapping a list, we might have something...