logical operators replacing if statements

logical-operators, pep8, python

Solution

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')

Problem

Are the following uses of logical expressions Pythonic / pep8 compliant? This: ``` x = a or b ``` instead of: ``` if not a: x = b else: x = a ``` This: ``` x = a and b ``` instead of: ``` if not a: x = a else: x = b ``` (The curve-ball?) This: ``` x = x or y ``` instead of: ``` if not x: x = y ```

Original source