Reputation: 8338
I'm trying to get a boolean True
or False
value based on whether a dict exists (is not None
) and if it contains a value.
This is my code. I would expect enabled == False
but it is assigned the value of cfg
.
In [105]: cfg = {}
In [106]: is_enabled = cfg and cfg.get('enabled')
In [107]: is_enabled
Out[107]: {}
Why is is_enabled == {}
? This must be an obvious mistake but I don't see it.
Upvotes: 4
Views: 2405
Reputation: 10946
Welcome to the world of short-circuit boolean operators. In the expression cfg and ANYTHING
, since cfg is empty it has a boolean value of False. Therefore the second operand is never evaluated. The result of the expression is the first operand, which is {}
. Note that the expression 0 and None
has a value of 0, but the expression 1 and None
has a value of None!
Perhaps you want the line to read is_enabled = bool(cfg) and cfg.get('enabled')
or even just is_enabled = cfg.get('enabled',False)
.
Upvotes: 4
Reputation: 152677
Depending on what you actually want to have to rewrite it
is_enabled = True if (cfg and cfg.get('enabled')) else False
cfg
only evaluates to False in a boolean context like if cfg
.
Upvotes: 3