Could anyone explain the expression that initializes mbr2
?
class MyClass(object):
def __init__(self, param1, param2=None):
self.mbr1 = param1
self.mbr2 = ({}, param2)[bool(param2)]
Thanks.
Could anyone explain the expression that initializes mbr2
?
class MyClass(object):
def __init__(self, param1, param2=None):
self.mbr1 = param1
self.mbr2 = ({}, param2)[bool(param2)]
Thanks.
The logic selects one of two values from the tuple depending on the truthiness of the param1
. If False
the tuple is indexed with 0, otherwise 1; bools are easily coerced to integers.
It can be more clearly expressed using a ternary operator:
self.mbr2 = param2 if param2 else {}
Or short-circuiting with or
:
self.mbr2 = param2 or {}
It is a (weird) way to do the following:
self.mbr2 = param2 if param2 else {}
That it's more Pythonic.
Basically it will choose between the two elements on tuple (({}, param2)
) if param2
is truthy(1) or falsy(0) (bool(param2)
)
whenever param1
is 'truthy', self.mbr2 = param1
. otherwise self.mbr2 = param1
.
note: True == 1
and False == 0
(and bool
returns one of these).
the more pythonic way is:
self.mbr2 = param2 if param2 else {}