@@ -231,31 +231,29 @@ since unless implemented by a sub-type, the expression will always evaluate to t
231231 if foo:
232232 ...
233233
234+ The check is similar in concept to ensuring that an expression's type implements an expected interface (e.g. ``Sized ``),
235+ except that attempting to invoke an undefined method (e.g. ``__len__ ``) results in an error,
236+ while attempting to evaluate an object in boolean context without a concrete implementation results in a truthy value.
234237
235- This check might falsely imply an error. For example, ``Iterable `` does not implement
236- ``__len__ `` and so this code will be flagged:
237238
238- .. code-block :: python
239+ Check that iterable is not implicitly true in boolean context [truthy-iterable]
240+ -------------------------------------------------------------------------------
239241
240- # Use "mypy -enable-error-code truthy-bool ..."
242+ ``Iterable `` does not implement ``__len__ `` and so this code will be flagged:
243+
244+ .. code-block :: python
241245
242246 from typing import Iterable
243247
244- def transform (items : Iterable[int ]) -> Iterable [int ]:
245- # Error: "items" has type "Iterable[int]" which does not implement __bool__ or __len__ so it could always be true in boolean context [ truthy-bool ]
248+ def transform (items : Iterable[int ]) -> list [int ]:
249+ # Error: "items" has type "Iterable[int]" which can always be true in boolean context. Consider using "Collection[int]" instead. [ truthy-iterable ]
246250 if not items:
247251 return [42 ]
248252 return [x + 1 for x in items]
249253
250-
251-
252- If called as ``transform((int(s) for s in [])) ``, this function would not return ``[42] `` unlike what the author
253- might have intended. Of course it's possible that ``transform `` is only passed ``list `` objects, and so there is
254- no error in practice. In such case, it might be prudent to annotate ``items: Sequence[int] ``.
255-
256- This is similar in concept to ensuring that an expression's type implements an expected interface (e.g. ``Sized ``),
257- except that attempting to invoke an undefined method (e.g. ``__len__ ``) results in an error,
258- while attempting to evaluate an object in boolean context without a concrete implementation results in a truthy value.
254+ If called with a ``Generator `` like ``int(x) for x in [] ``, this function would not return ``[42] `` unlike
255+ what the author might have intended. Of course it's possible that ``transform `` is only passed ``list `` objects,
256+ and so there is no error in practice. In such case, it is recommended to annotate ``items: Collection[int] ``.
259257
260258
261259Check that function isn't used in boolean context [truthy-function]
0 commit comments