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

前端 未结 8 584
旧巷少年郎
旧巷少年郎 2020-12-02 04:27

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 m

8条回答
  •  生来不讨喜
    2020-12-02 04:39

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

提交回复
热议问题