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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With