Skip to main content

truthassert: The PythonAssert That Can Never Fail

assert (cond, "msg") asserts a tuple, and a tuple is always true, so the check never fires. A tiny AST gate catches it in CI.

Updated 6 min readMarkdown
truthassert: The PythonAssert That Can Never Fail

Here is a line of Python that looks like it defends an invariant, passes code review, runs in production for two years, and defends nothing at all:

assert (ratio > 0, "ratio must be positive")

Read it quickly and your eye fills in the meaning you expect: "assert that ratio > 0, and if it isn't, complain that the ratio must be positive." That is not what runs. In Python a comma builds a tuple, and the parentheses only group it. So the thing being asserted is a two-element tuple object - and a non-empty tuple is always truthy. The assertion can never fail. Feed it ratio = -5 and it sails straight through.

The author meant this, with the parentheses removed:

assert ratio > 0, "ratio must be positive"

One character of punctuation - a pair of parentheses - is the whole difference between a real guard and a dead one. I wrote truthassert, a tiny zero-dependency CLI, because this bug is easy to type, nearly invisible in review, and silent at runtime in the worst possible way.

Why this is worse than a crash

A check that always raises is annoying but honest - you find it on the first run. A check that can never fire is the dangerous kind. It gives you the comfort of a guard without the guard. Every reader afterward assumes the invariant is enforced, builds on that assumption, and the day the condition is finally violated, nothing happens. The bad ratio, the empty list, the negative balance flows downstream and surfaces somewhere far from the assert that was supposed to stop it.

There are three shapes of the same mistake, and they split into two runtime behaviours:

You wrote What Python sees Runtime
assert (cond, "msg") a 2-element tuple always true - never fails
assert (x,) a 1-element tuple (trailing comma) always true - never fails
assert () the empty tuple always false - always raises

The first is the classic footgun. The second usually comes from a stray trailing comma that turns a bare value into a one-tuple. The third is the mirror image: the empty tuple is the one falsy tuple, so assert () blows up on every call. All three share one root cause - the thing after assert is a tuple literal, not the boolean the author intended.

"Doesn't Python already warn about this?"

It does, partially. CPython emits SyntaxWarning: assertion is always true, perhaps remove parentheses? for the obvious multi-element case. That warning is genuinely helpful - and genuinely easy to lose:

  • It is a warning printed to stderr at compile time, drowned in the noise of a busy test run, and it never fails CI.
  • It is suppressed entirely when you run with python -O.
  • It does not fire for the one-element tuple from a trailing comma, nor for the always-false empty tuple.
  • Linters are inconsistent here; plenty of real projects ship the bug anyway.

truthassert turns a miss-prone warning into a deterministic, greppable finding with a non-zero exit code you can actually gate a pipeline on - and it covers all three shapes.

How it works

The implementation is deliberately small because the detection is exact. There is no heuristic, no scoring, no guessing. truthassert parses each file with the standard-library ast module and visits every assert statement. The rule is one line of logic:

Flag the assert if, and only if, node.test is an ast.Tuple.

class _Visitor(ast.NodeVisitor):
    def visit_Assert(self, node):
        if isinstance(node.test, ast.Tuple):
            n = len(node.test.elts)
            # n == 0 -> always false; otherwise always true
            self.record(node, kind="empty" if n == 0 else
                               "single" if n == 1 else "multi")
        self.generic_visit(node)

This is why the false-positive rate is essentially zero. A correctly written assertion is parsed with its test and its message as separate children of the Assert node - test=Compare(...) and msg=Constant("..."). The test is not a tuple, so it is never flagged. The detector only fires when the test node itself is a tuple literal.

What it does not flag

Low noise was the design goal, so the cases that merely look related are all left alone:

assert x > 0, "bad"            # correct form - test is `x > 0`; clean
assert x                        # bare condition; clean
assert isinstance(t, tuple)     # tests a Call, not a tuple literal; clean
assert x in (1, 2, 3)           # the tuple is an operand; the test is a Compare; clean
assert (x > 0), "bad"           # parens just group a comparison; clean

The last one is worth dwelling on: parentheses are not the problem - a comma inside them is. assert (x > 0) is a grouped comparison and perfectly fine; assert (x > 0,) is a one-tuple and a bug. truthassert tells them apart because it reads the parse tree, not the text.

The one honest edge

Could someone genuinely want to assert the truthiness of a real tuple value, as in assert (a, b)? In theory, yes. In practice it is near-nonexistent, and since a non-empty tuple is always truthy, such an assert is pointless regardless - it asserts nothing. So flagging it costs nothing. For the vanishingly rare intentional case, a suppression comment opts out:

assert (a, b)  # truthassert: ignore

Using it

pip install truthassert

truthassert src/ tests/      # scan directories and/or files
cat app.py | truthassert -   # read stdin
truthassert --json src/      # machine-readable output

Exit codes are CI-native: 0 clean, 1 at least one finding, 2 a usage error. Output points straight at the line:

TUPLE-ASSERT TA-TUPLEASSERT app.py:11:4  `assert (...)` tests a 2-element
    tuple, which is always truthy - this assertion can never fail; the message
    was swallowed into the tuple.
        assert (0 <= pct <= 100, "percent must be between 0 and 100")
        ↳ Drop the parentheses: write `assert cond, "message"`.

Drop it into a pipeline in two lines:

- run: pip install truthassert
- run: truthassert src/ tests/

Where it fits

truthassert does exactly one thing. It is not a test-coverage tool and it is not a security linter - two adjacent ideas it is worth separating from explicitly. Checking whether a test function has any assertions at all is a coverage question. Checking whether an assert is being (mis)used as a production access-control gate that python -O would strip is a security question. truthassert is narrower than both: it catches a single assert statement that is structurally a tuple and therefore a dead check, independent of coverage and independent of optimizer flags. A pure code-correctness bug, caught by reading the parse tree.

It is MIT-licensed, dependency-free, and runs on Python 3.8 and up.

Repo: github.com/jay-tank/truthassert

About the author

  • Cloud & Platform Engineer focused on building systems that scale and endure. I explore how infrastructure, automation, and engineering practices come together to support modern software teams.

"The comfort of a guard without the guard" is the line I'd keep. Coming from carpentry and estimating, this is an inspection sticker that got printed before the inspector showed up. Everyone after that builds on it, and the failure turns up three trades later, far from the check that was supposed to catch it. The comma inside the parentheses being the whole bug is a good example of why reading the tree beats reading the text. It looks right to a person, which is how it gets past review. I direct agents as a Language Modeler, and a check that can't fail is the first thing I look for in generated tests. Narrow tools that catch one thing are easy to trust.

More from this blog