Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 859
PiCTo Avatar asked Dec 01 '19 17:12

PiCTo


1 Answers

We could use partial as an alternative to lambda:

from functools import partial
from collections import defaultdict

d_true = defaultdict(partial(bool, True))

print(d_true['bona fide'])

(Which is also Python 2 friendly.)

like image 168
cdlane Avatar answered Oct 02 '22 15:10

cdlane