2

Instead of writing

a = a or b

for Booleans a and b, I would like to write something like:

a |= b (or equals)

but this doesn't work. Is there an equivalent to this concise statement in Python? Thanks.

9
  • 2
    You could do that. But |= DOES work, so...? Commented Oct 21, 2016 at 12:12
  • 2
    a |= b does work, please show an example where it doesn't Commented Oct 21, 2016 at 12:12
  • Sorry, I missed that. You're right. Commented Oct 21, 2016 at 12:13
  • 2
    Still very different. In the first example, or acts like a null coalescing operator whereas | does bitwise or in the second one. Do print 3 or 5 and 3 | 5 and compare results. Commented Oct 21, 2016 at 12:14
  • a |= b works iff both are booleans. For everything else use a = a or b, or a |= bool(b) if a is a boolean. Commented Oct 21, 2016 at 12:16

1 Answer 1

1

Please note that

a = a or b

Won't return a boolean per se, but will return a if evaluated truthy (so if it's -1, 1, "a", obj, etc)

| In python (and most languages) is a Bitwise operator

I'm afraid a or b is as short as it gets. But it's already much better than using ternary expression like in C

condition ? expr1 : expr2 

In Python

a = a if a else b
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.