3 ms·
I hypothesise that the actual meaning (possibly subconscious) underlying those uses of "complicated", "syntactic sugar", and "clever code" is 'not the way I'd w
by chriswarbo 5y ago
I hypothesise that the actual meaning (possibly subconscious) underlying those uses of "complicated", "syntactic sugar", and "clever code" is 'not the way I'd write it'; and that "clarity" and "clean" actually mean 'the way I would write it'.
To test whether those statements are guiding principles, or merely ad-hoc justifications, I propose the following pylint rules based on those principles:
no-ternary-sugar:
Replace 'x if y else z' with '{True: lambda: x, False: lambda: z}[y]()'.
This is less concise, but improves clarity by using booleans explicitly,
and making the delayed evaluation of the results clear; both of which are
implicit in the 'if/else' syntactic sugar.
no-elif-sugar:
Replace:
if foo:
bar
elif baz:
quux
...
else:
foobar
With:
if foo:
bar
else:
if baz:
quux
else:
...
else:
foobar
This is less concise, but makes the branching structure clear, unlike the misleading
"flat" appearance of the 'elif' syntactic sugar.
no-special-case-patterns:
Replace:
if foo:
bar
else:
baz
With:
match foo:
case True:
bar
case False:
baz
'if/else' is syntactic sugar for pattern-matching a boolean, which is left implicit.
Explicit matching improves consistency with other use-cases, and makes the relationship
between branches and boolean clear, at the expense of conciseness.
(Also applies to single-armed 'if', which will only have a 'case True:').
Of course, the combination of no-elif-sugar and no-special-case-patterns would give extreme clarity like this:
match foo:
case True:
bar
case False:
match baz:
case True:
quux
case False:
...
case False:
foobar