Skip to content

feat: q to bool#2227

Open
VladislavYar wants to merge 1 commit into
tortoise:developfrom
VladislavYar:q-to-bool
Open

feat: q to bool#2227
VladislavYar wants to merge 1 commit into
tortoise:developfrom
VladislavYar:q-to-bool

Conversation

@VladislavYar

Copy link
Copy Markdown

Description

Added __bool__ support to the Q class, allowing Q objects to be evaluated in a boolean context.

A Q object is considered truthy if it contains any filters or any non-empty children. An empty Q() with no filters and no children evaluates to False.

Motivation and Context

Previously, all Q instances were truthy by default (standard Python object behavior), making it impossible to distinguish between an empty Q() and a meaningful one. This change enables natural boolean checks like if q: to guard against applying empty query conditions.

How Has This Been Tested?

Added test_q_to_bool covering four cases:

Q(row="data") - truthy (has filters)
Q() - falsy (no filters, no children)
Q(Q(row="data"), Q(row="data")) - truthy (has non-empty children)
Q(Q(), Q()) - falsy (all children are empty)

Checklist:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added the changelog accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

@codspeed-hq

codspeed-hq Bot commented Jun 24, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 24 untouched benchmarks


Comparing VladislavYar:q-to-bool (67f957a) with develop (bc4f971)

Open in CodSpeed

Comment thread tests/test_q.py
assert bool(q_empty) is False
assert bool(q_children) is True
assert bool(q_children_empty) is False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add more test cases, such as:

q = ~q
q = Q(Q(), Q(), join_type='OR')
...

Comment thread tortoise/expressions.py
)

def __bool__(self) -> bool:
return any((self.filters, *(children for children in self.children)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about using the following code?

if self.filters:
    return True
return any(self.children)

@waketzheng waketzheng left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to also update the changelog.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants