Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logical operators replacing if statements

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
    
like image 430
Scruffy Avatar asked Aug 18 '13 14:08

Scruffy


2 Answers

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.

like image 139
Viktor Kerkez Avatar answered Sep 24 '22 06:09

Viktor Kerkez


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')
like image 30
Blender Avatar answered Sep 22 '22 06:09

Blender