@@ -231,31 +231,29 @@ since unless implemented by a sub-type, the expression will always evaluate to t
231
231
if foo:
232
232
...
233
233
234
+ This 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.
234
237
235
- This check might falsely imply an error. For example, ``Iterable `` does not implement
236
- ``__len__ `` and so this code will be flagged:
237
238
238
- .. code-block :: python
239
+ Check that iterable is not implicitly true in boolean context [truthy-iterable]
240
+ -------------------------------------------------------------------------------
241
+
242
+ ``Iterable `` does not implement ``__len__ `` and so this code will be flagged:
239
243
240
- # Use "mypy -enable-error- code truthy-bool ..."
244
+ .. code-block :: python
241
245
242
246
from typing import Iterable
243
247
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 ]
246
250
if not items:
247
251
return [42 ]
248
252
return [x + 1 for x in items]
249
253
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] ``.
259
257
260
258
261
259
.. _ignore-without-code :
0 commit comments