A dictionary can be automatically cast to boolean which evaluates to False
for empty dictionary and True
for non-empty dictionary.
if myDictionary: non_empty_clause()
else: empty_clause()
If this looks too idiomatic, you can also test len(myDictionary)
for zero, or set(myDictionary.keys())
for an empty set, or simply test for equality with {}
.
The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.
- The
return False
statement is indented one level too deep. It should be outside the for loop and at the same level as the for
statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None
, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives.
- If the dictionary is not empty, then the code will process only one key and return its value cast to boolean. You cannot even assume that the same key is evaluated each time you call it. So there will be false positives.
- Let us say you correct the indentation of the
return False
statement and bring it outside the for
loop. Then what you get is the boolean OR of all the keys, or False
if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.
myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}
self.users
is nonempty, just doif self.users
. – BrenBarnisEmpty
actually returnsTrue
if the first key yielded from the dictionary is truey and returnsFalse
otherwise. If the dictionary is empty, it returnsNone
which is not== False
. – Hyperboreus