Question

Are the following uses of logical expressions Pythonic / pep8 compliant?

  1. This:

    x = a or b
    

    instead of:

    if not a:
        x = b
    else:
        x = a
    
  2. This:

    x = a and b
    

    instead of:

    if not a:
        x = a
    else:
        x = b
    
  3. (The curve-ball?) This:

    x = x or y
    

    instead of:

    if not x:
        x = y
    
Was it helpful?

Solution 2

Unlike C and Java, Python's logical operators don't return booleans. I can't imagine another use case for that language feature besides the one in your question, so unless the language designers are adding features thoughtlessly, it's Pythonic (except for #3).

There are many cases where the short-circuiting logical OR can be used to your advantage. Here's a simple one from the source code of Requests:

cookies = request.cookies or {}

It's immediately obvious what the outcome of this code should be, as it reads like a sentence. Now that's not to say that the verbose versions aren't readable:

cookies = request.cookies if request.cookies else {}

And:

cookies = {}

if request.cookies:
    cookies = request.cookies

But they're redundant. Python uses the same syntax for dictionaries to prevent the same sort of redundancy:

d.get('key', 'fallback')

OTHER TIPS

PEP 8 has nothing to do with the way you use your logical operators.

Assuming the motivation for using the logic operators instead of the conditionals is brevity, then it is better accomplished with the ternary operator:

  1. x = a if a else b instead of x = a or b

  2. x = b if a else a instead of x = a and b

  3. x = x if x else y or just if not x: x = y instead of x = x or y

But nobody forbids you to use the other versions too. It's all a meter of personal opinion. The motivation behind introduction of the ternary operator was to avoid the error-prone attempts to achieve the same effect using the and and or operators (see PEP 308). They also enable fancy stuff in list comprehensions, and a few more things.

They are not introduced to replace complex if statements, but as a pythonic ternary operator: x if condition else y.

I don't think pep8 covers this, but to me, in your examples, the if statements look more readable (especially to people new to Python (and therefore more Pythonic due to "readability counts") than logical operators, which still look more Pythonic than ternary operators.

However, ternary operators are definitely better than condition and true_value or false_value, (false_value, true_value)[condition] etc. due to being more readable and less likely to break.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top