1

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.

3 Answers3

3

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 {}
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
3

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))

Rafael Aguilar
  • 3,084
  • 1
  • 25
  • 31
0

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 {}
Community
  • 1
  • 1
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111