Replies: 2 comments 1 reply
-
Some more materials for reference:
|
Beta Was this translation helpful? Give feedback.
0 replies
-
@kkom did you find any tool which implements this check? |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Suggestion
Ban code like this:
Examples of code that would pass this rule:
I don't think an autofixer for this rule is needed, or even desired – as the motivation is for the programmer to be explicit about what conditions they are evaluating, rather than relying an implicit catch-all check.
int
is just an example, but I would like the rule to flag such usage of any type other thanbool
(so alsostr
,list
,set
, custom objects – everything).Motivation
Python allows any object to be used in conditionals (
if
,while
or as an operand of boolean operations) – thanks to the__bool__()
and__len__()
special methods. See:__bool__
__len__
However, this behaviour is quite implicit and can lead to undesired outcomes. In my opinion, it at the least hides nuanced logic and makes the code non-obvious – more difficult to read and reason about.
0
as falsy, but any otherint
as truthy.int
), but not if it wasn't (None)
– writing justif x: ...
results in bundling "good"0
values with the "bad"None
values.""
is often considered undesired, but it is still distinct fromNone
and may be sometimes fine.[]
or setset()
– they occasionally represent perfectly correct values (empty, rather than missing data), which a sloppyif x: ...
check would discard.More generally, Python (unlike e.g. Java or Go) has the great advantage of having an explicit
None
type, which type checkers like mypy and Pyright understand and refine through advanced static type inference (e.g. flow-sensitive typing).This makes it possible to lean on optional types like
str | None
,int | None
,list[object] | None
andx is None
checks – allowing the type checker to refine the types and avoid checks being redundantly repeated:To benefit from this, some codebases will even define custom types such as:
Where
NonEmptyString | None
can be passed around and tested for bad data exactly once.A "no truthy check" rule like this would be intended to be used in such codebases.
PS: It's inspired by Facebook's PHP/Hack rule called
no-sketchy-null-check
(I forget the exact name). It's the opposite of PLC1901, so they shouldn't be both enabled at the same time.Questions
Beta Was this translation helpful? Give feedback.
All reactions