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()))
Answer from user2555451 on Stack OverflowEmpty 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"
Videos
if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite Pythonic.
The Pythonic way to do it is from the PEP 8 style guide.
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
# Correct: if not seq: if seq: # Wrong: if len(seq): if not len(seq):
I'm trying to constantly check against any of those values but I don't want to keep repeating myself in code.
if variable is None or variable == "": do stuff
What are my options? Can I create somehow a class and check against that class?
if variable is MyNewClass: do stuff
How would I write such a class?
Thanks!
You need to implement the __nonzero__ method (or __bool__ for Python3)
https://docs.python.org/2/reference/datamodel.html#object.nonzero
class my_class(object):
def __init__(self):
self.lis1 = []
self.dict1 = {}
def __nonzero__(self):
return bool(self.lis1 or self.dict1)
obj = my_class()
if obj:
print "Available"
else:
print "Not available"
Python also checks the __len__ method for truthiness, but that doesn't seem to make sense for your example.
If you have a lot of attributes to check you may prefer to
return any((self.lis1, self.dict1, ...))
The build in vars() function makes a useful one-liner for checking if an object has any non-empty attributes. Combine it with __nonzero__ and you get the following:
def __nonzero__(self):
return any(vars(self).values())