Wemake-python-styleguide: Forbid to use ternary inside `if` clause

Created on 11 Jul 2019  路  4Comments  路  Source: wemake-services/wemake-python-styleguide

Rule request

Thesis

One can write code like this:

if one if some() else two:
    ...

Reasoning

This is unreadable.
Use nested ifs instead.

help wanted starter rule request

Most helpful comment

Ok, after some thinking, let's return to the original idea: we will only disallow ternaries inside:

  • if
  • compare
  • boolop (>, +, *, ==, etc)
  • unary: -(x if cond() else y)

All 4 comments

Well, actually the rule is even stricter.
We should not be able to nest ternary anywhere except:

  • ast.Assign and ast.AnnAssign as a value
  • open to suggestions

@sobolevn Why you forbid to use ternary but allow in some cases? It's kinda weird.

@AlwxSin yeap, since it is absolutely fine to write:

some = x if cond() else y  # sure is

print(x if cond() else y)  # is it?

But it is not ok to nest ternary inside a condition:

x > (x if cond() else y)  # what?!

Ok, after some thinking, let's return to the original idea: we will only disallow ternaries inside:

  • if
  • compare
  • boolop (>, +, *, ==, etc)
  • unary: -(x if cond() else y)
Was this page helpful?
0 / 5 - 0 ratings