WoJ WoJ - 1 year ago 44
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

Note: I know I can simply have
a = True
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
, etc. are OK, I would just prefer to specifically have a
initialized as

Answer Source

You can use functools.partial to customize your bool:

from functools import partial

my_bool = partial(bool, 1)

# 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