Expose the number of stored elements through len().
Custom containers
Python · Module
__len__ implements the built-in len() operation for an object. It should return a non-negative integer, and a zero result supplies falsey behavior when __bool__ is not defined.
Define __len__ to let instances work with the built-in len() function. Return a non-negative integer representing the object’s size; unless __bool__ is defined, a zero result also makes the instance false in Boolean contexts.
object.__len__(self)| Name | Type | Description |
|---|---|---|
self | object | The instance whose length is being reported. |
A non-negative integer giving the object’s length.
class Queue:
def __init__(self, items=()):
self._items = list(items)
def __len__(self):
return len(self._items)
queue = Queue(["job-1", "job-2"])
print(len(queue))
print(bool(queue))The class delegates its length to the underlying list, so len() returns 2 and the nonzero length makes the instance truthy.
Custom containers
Resource or collection wrappers
Boolean checks
Implementing __len__ lets an object respond to the built-in len() function. It should return an integer that is at least zero.
Follow-up: What happens in an if statement when __bool__ is absent? A zero __len__ result makes the object false; a nonzero result makes it true.
The method receives only self and returns the object’s length. It is the special-method hook used by len().
Follow-up: How should a container implement it? Return the size of its authoritative internal collection, avoiding a separately maintained value that can become stale.
A class with __len__ can participate in Boolean contexts even without defining __bool__. If __len__ returns zero, Python treats the object as false.
Follow-up: How can a class choose truthiness independently of size? Define __bool__ so Boolean evaluation does not rely on __len__.
__bool__len()__getitem____iter__