Python: Checking if a 'Dictionary' is empty doesn't seem to work

Unsparing picture Unsparing · Apr 20, 2014 · Viewed 593k times · Source

I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays ONLINE without anything except of display the message. Any ideas why ?

def isEmpty(self, dictionary):
    for element in dictionary:
        if element:
            return True
        return False

def onMessage(self, socket, message):
    if self.isEmpty(self.users) == False:
        socket.send("Nobody is online, please use REGISTER command" \
                 " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))    

Answer

user2555451 picture user2555451 · Apr 20, 2014

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