truth value of empty user-defined data objects

47 Views Asked by At

This is more of a philosophical question.

In python, bool([]) evaluates to False. On the other hand, consider the following:

from dataclasses import dataclass


@dataclass
class Lists:
    items: list[str]
    other_items: list[str]


assert bool(Lists(items=[], other_items=[]))

The above snippet doesn't raise AssertionError.

Why is that?

I encountered a use-case where it seems to make sense to deduce an object's truth value by aggregating the truth values of its attributes.

Are there any caveats to keep in mind before doing so?

(I'm talking about data classes, like dataclass or pydantic.BaseModel)

1

There are 1 best solutions below

0
SIGHUP On

An instance of a Python class is always truthy unless it implements __bool__() or __len__()

Simple example:

class FOO():
    def __init__(self, x:str|None=None):
        self._x = x
    def __bool__(self) -> bool:
        return self._x is not None


class BAR:
    def __init__(self, x:str|None=None):
        self._x = x
    def __len__(self) -> int:
        return 0 if self._x is None else len(self._x)

print(bool(FOO()))
print(bool(FOO("hello")))
print(bool(BAR()))
print(bool(BAR("hello")))

Output:

False
True
False
True