Истинностное значение пустых пользовательских объектов данныхPython

Программы на Python
Anonymous
Истинностное значение пустых пользовательских объектов данных

Сообщение Anonymous »


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)


Источник: https://stackoverflow.com/questions/781 ... ta-objects

Вернуться в «Python»