0

I have an API response that can respond with an array like this:

[
    {
        "id": 1,
        "title": "Warning"
    },
    {
        "id": 2,
        "title": "Warning"
    }
]

sometimes it can respond just empty array

[]

in my case i created a class for this object. Something like this:

class Warning:
    def __init__(self, data: Dict):
        if bool(data):
            self.id: int = data["id"]
            self.title: str = data["title"]
        else:
            pass


if __name__ == '__main__':
    data = {
        "id": 123455,
        "title": "Warning"
    }
    empty_data = {}
    object1: List[Warning] = [Warning(data)]
    object2: List[Warning] = [Warning(empty_data)]
    if object1:
        print("we have a warnings")
    if object2:
        print("we don't have warnings")

I can't understand, how can I check if i get List of Object with empty fields like object2?

  • https://stackoverflow.com/a/23177452/7157435 – ShivCK Feb 07 '22 at 17:19
  • 3
    Use `if data:` or `if len(data) > 0:` to test for a non-empty list. Typically the former. – jarmod Feb 07 '22 at 17:20
  • I've tried this and in my case it always returns true. This is because i put object into a list and list is always has length. And i want to check that object is created properly with data – Ilya Zaytsev Feb 08 '22 at 15:21

1 Answers1

0

I would suggest looking at the __bool__ class method which enables you to determine the boolean value of a python class.

However, you will also need to decide what the boolean value of the list should be e.g. should bool([Warning(empty_data), Warning(data)]) return False or True?

  • That worked for me. Thanks! In class i created `__bool__` function which check if object has attribute of properly created fields – Ilya Zaytsev Feb 08 '22 at 15:17