{"record":{"id":"a747bba2d1c9b797","repo":"pola-rs/polars","slug":"the-truth-value-of-a-lazyframe-is-ambiguous-lazyf","errorCode":null,"errorMessage":"the truth value of a LazyFrame is ambiguous\n\nLazyFrames cannot be used in boolean context with and/or/not operators.","messagePattern":"the truth value of a LazyFrame is ambiguous\n\nLazyFrames cannot be used in boolean context with and/or/not operators\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/lazyframe/frame.py","lineNumber":663,"sourceCode":"        ...     }\n        ... )\n        >>> lf.width  # doctest: +SKIP\n        2\n        \"\"\"\n        issue_warning(\n            \"determining the width of a LazyFrame requires resolving its schema,\"\n            \" which is a potentially expensive operation. Use `LazyFrame.collect_schema().len()`\"\n            \" to get the width without this warning.\",\n            category=PerformanceWarning,\n        )\n        return self.collect_schema().len()\n\n    def __bool__(self) -> NoReturn:\n        msg = (\n            \"the truth value of a LazyFrame is ambiguous\"\n            \"\\n\\nLazyFrames cannot be used in boolean context with and/or/not operators.\"\n        )\n        raise TypeError(msg)\n\n    def _comparison_error(self, operator: str) -> NoReturn:\n        msg = f'\"{operator!r}\" comparison not supported for LazyFrame objects'\n        raise TypeError(msg)\n\n    def __eq__(self, other: object) -> NoReturn:\n        self._comparison_error(\"==\")\n\n    def __ne__(self, other: object) -> NoReturn:\n        self._comparison_error(\"!=\")\n\n    def __gt__(self, other: Any) -> NoReturn:\n        self._comparison_error(\">\")\n\n    def __lt__(self, other: Any) -> NoReturn:\n        self._comparison_error(\"<\")\n\n    def __ge__(self, other: Any) -> NoReturn:","sourceCodeStart":645,"sourceCodeEnd":681,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/lazyframe/frame.py#L645-L681","documentation":"`LazyFrame.__bool__` (frame.py:663) is deliberately disabled: a LazyFrame represents an unexecuted query, so its truth value (empty? any rows? any columns?) is undefined and computing it would silently trigger an expensive `collect`. Any boolean-context use — `if lf:`, `not lf`, `lf and x`, `bool(lf)`, `assert lf` — raises TypeError with guidance pointing away from and/or/not operators.","triggerScenarios":"`if not lf: ...`, `lf1 or lf2`, `assert lf` on any `LazyFrame`; also `bool(lf)` or passing a LazyFrame where Python implicitly coerces truthiness (e.g. `any([lf])`, ternaries).","commonSituations":"Pandas habits (`if df.empty():`, truthiness checks) carried over to lazy APIs; guard clauses like `if lf is None or lf:`; template/ORM code that truth-tests arbitrary objects; refactoring eager code to lazy without adjusting emptiness checks.","solutions":["Execute and check rows: `if lf.collect().height > 0:` or `if not lf.collect().is_empty():`","To check the query produces columns, use `len(lf.collect_schema()) > 0` (schema resolution only, no full scan)","For None-or-frame checks use `is None` explicitly, never bare truthiness","Avoid `assert lf` in tests; assert on collected results or plans instead"],"exampleFix":"# before\nif not lf:\n    raise ValueError('empty')  # TypeError: truth value ambiguous\n\n# after\nif lf.collect().is_empty():\n    raise ValueError('empty')","handlingStrategy":"type-guard","validationCode":"import polars as pl\n\ndef nonempty(lf: pl.LazyFrame) -> bool:\n    'Explicit emptiness check that runs the query.'\n    return lf.collect().height > 0\n\ndef has_columns(lf: pl.LazyFrame) -> bool:\n    'Cheap check that only resolves the schema.'\n    return len(lf.collect_schema()) > 0\n\nif nonempty(lf):  # instead of: if lf:\n    ...","typeGuard":"from typing import TypeGuard\nimport polars as pl\n\ndef is_lazy_frame(x: object) -> TypeGuard[pl.LazyFrame]:\n    return isinstance(x, pl.LazyFrame)\n\n# use before any boolean context on mixed values:\nif is_lazy_frame(obj):\n    check = obj.collect().height > 0\nelse:\n    check = bool(obj)","tryCatchPattern":"try:\n    ok = bool(lf)\nexcept TypeError as e:\n    if 'truth value of a LazyFrame is ambiguous' in str(e):\n        ok = lf.collect().height > 0\n    else:\n        raise","preventionTips":["Never truth-test LazyFrames; write lf is None explicitly for None checks","Replace pandas-style if df: with lf.collect().is_empty() / .height in ported code","Lint for `if <name>:` over known-lazy variables; add a unit test for emptiness helpers","Remember any boolean context counts: and/or/not, ternaries, assert, any()/all()"],"tags":["polars","lazyframe","boolean","typeerror"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}