Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object attributes are non-empty python

I can check if python list or dictionary are empty or not like this

lis1, dict1 = [], {}
# similar thing can be done for dict1
if lis1:
    # Do stuff
else:
    print "List is empty"

If I try to do this with my class object, i.e checking if my object attributes are non-empty by typing if my_object: this always evaluate to True

>>> class my_class(object):
...   def __init__(self):
...     self.lis1 = []
...     self.dict1 = {}
... 
>>> obj1 = my_class()
>>> obj1
<__main__.my_class object at 0x10c793250>
>>> if obj1:
...   print "yes"
... 
yes

I can write a function specifically to check if my object attributes are non-empty and then call if obj1.is_attributes_empty():, but I am more interested in knowing how if evaluates the standard data-types like list and dict to True or False depending on the items they contain or are empty.

If I want to achieve this functionality with my class object, what methods do I need to override or make changes to?

like image 767
Anurag Sharma Avatar asked Sep 29 '15 05:09

Anurag Sharma


People also ask

How do you check an object is empty or not in Python?

You can check if the list is empty in python using the bool() function. bool() function returns boolean value of the specified object. The object will always return True , unless the object is empty, like [] , () , {} . You can use the bool() function for any of the list-like objects.

How do you know if an object has an attribute in Python?

We can use hasattr() function to find if a python object obj has a certain attribute or property. hasattr(obj, 'attribute'): The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block.


2 Answers

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, ...))
like image 89
John La Rooy Avatar answered Oct 15 '22 11:10

John La Rooy


It is given in the documentation of Truth value testing for Python 2.x -

instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

For Python 3.x -

instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.

According to the definition of your class, if maybe meaningful to define __len__() method, which returns the sum of length of the list as well as the dict.Then this method would be called to determine whether to interpret the object as True or False in boolean context. Example -

class my_class(object):
    def __init__(self):
        self.lis1 = []
        self.dict1 = {}
    def __len__(self):
        print("In len")
        return len(self.lis1) + len(self.dict1)

Demo -

>>> class my_class(object):
...     def __init__(self):
...         self.lis1 = []
...         self.dict1 = {}
...     def __len__(self):
...         print("In len")
...         return len(self.lis1) + len(self.dict1)
...
>>> obj = my_class()
>>> if obj:
...     print("yes")
...
In len
>>> obj.lis1.append(1)
>>>
>>> if obj:
...     print("yes")
...
In len
yes
like image 28
Anand S Kumar Avatar answered Oct 15 '22 10:10

Anand S Kumar