Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get True or False from dict and key's existence

Tags:

python

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.

like image 263
skyler Avatar asked Sep 19 '25 22:09

skyler


1 Answers

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

like image 151
Paul Cornelius Avatar answered Sep 21 '25 11:09

Paul Cornelius