Pergunta

PEP 8 discourages the usage of compound statements, but I couldn't find anything about the advised usage of Python's ternary/conditional syntax. For example:

return x if n == 0 else y
i = x if n == 0 else y if n == 1 else z

Does there exist any convention concerning whether the above statements should be preferred to more traditional if/else blocks?

if n == 0:
    return x
return y

if n == 0:
    i = x
elif n == 1:
    i = y
else:
    i = z
Foi útil?

Solução

The "traditional if/else blocks" should generally be preferred.

The only places where you'd still want to use the ternary operator is in places where the syntax requires an expression, e.g. within lambda expressions. Even there, only do it if the ternary expression is short and readable (of course, readability is subjective..)

You can always replace a lambda expression with a small function, but in places where you think that would make the code less readable, it is ok to use lambda expressions with short ternary operations.

Outras dicas

I agree with shx2's comments.

Another consideration is testability... using the ternary expr places all the logic on a single line/expr. Basic line-base code coverage tools wouldn't then give a good read on the true coverage of your tests.

Using traditional is/else blocks gives a better reading.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top