WoJ WoJ - 5 months ago 7
Python Question

Is it possible to initialize a bool with True?

I am defining a variable through an empty declaration:

In [1]: a = bool()

In [2]: a
Out[2]: False


Is it possible to force an initialization of
True
?




Note: I know I can simply have
a = True
or
a = bool(True)
but I will be initializing several variables with specific types, something like

x = dict()
for v in [('a', int), ('b', float), ('c', bool)]
x[v[0]] = v[1]()


The defaults for
int
,
float
, etc. are OK, I would just prefer to specifically have a
bool
initialized as
True

Answer

You can use functools.partial to customize your bool:

from functools import partial

my_bool = partial(bool, 1)

print(my_bool())
# True

And you can use it in your code as:

x = dict()
for v in [('a', int), ('b', float), ('c', my_bool)]
    x[v[0]] = v[1]()

You could also use a lambda (credit: @tobias_k):

my_bool = lambda: True