Search code examples
pythongenerator

Most pythonic callable generating True?


The class collections.defaultdict takes a default factory, used to generate a default value.

If the values contained in the dict-like object should default to False, the instance can be created as:

d_false = defaultdict(bool)

What is the most pythonic way to achieve the same for a default value of True?

In other terms, is there a standard callable object returning True which is idiomatically used as the relative of bool?

Of course, the factory could be built as a lambda expression:

d_true = defaultdict(lambda: True)

but this might be reinventing the wheel.


Solution

  • Well, you can do

    d = defaultdict(True.__bool__)
    

    but I personally would go with the lambda: True.