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?

3
  • stackoverflow.com/a/23177452/7157435 Commented Feb 7, 2022 at 17:19
  • 3
    Use if data: or if len(data) > 0: to test for a non-empty list. Typically the former. Commented Feb 7, 2022 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 Commented Feb 8, 2022 at 15:21

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

That worked for me. Thanks! In class i created __bool__ function which check if object has attribute of properly created fields

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.