Call dict with no parameters
Copynew_dict = dict()
or simply write
Copynew_dict = {}
Answer from Jan Vorcak on Stack OverflowWhy does my empty dictionary not evaluate to false?
Why is it common in python to make an empty list or dict first?
Videos
Empty dictionaries evaluate to False in Python:
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
Thus, your isEmpty function is unnecessary. All you need to do is:
def onMessage(self, socket, message):
if not self.users:
socket.send("Nobody is online, please use REGISTER command" \
" in order to register into the server")
else:
socket.send("ONLINE " + ' ' .join(self.users.keys()))
Here are three ways you can check if dict is empty. I prefer using the first way only though. The other two ways are way too wordy.
test_dict = {}
if not test_dict:
print "Dict is Empty"
if not bool(test_dict):
print "Dict is Empty"
if len(test_dict) == 0:
print "Dict is Empty"
dict_a = {}
print(dict_a)
print(dict_a == False)
print(bool(dict_a) == False)Why do we need the bool function to check whether a sequence is empty not not? I keep thinking if a list or dictionary is empty it automatically evaluates to none. So why do we need to explicitly check the boolean of an object?
Something I've never understood with python is why it is so common for an empty list to be created and then populated with something in a subsequent (or even more common next) line:
my_list = [] my_list = [i for i in range(1, 21)]
Obviously this is a really really toy example, but I'm consistently finding this in "production" code in multiple places. Is it pythonic? It's basically pure duplication so I doubt it. Is it some hacky "optimisation"? Is it a side effect of the code priorly being a for loop, then turned to a list comprehension but not tidied up right?
I honestly just feel ike I'm missing something key, with the amount of times and variety of places I see this pattern.