Moberg
Moberg

Reputation: 5503

Does python have an assignment operator for logical or?

Is there any way to to logical-or-assignment in python? Much like a += 5

I would like to be able to do something like this:

a = True
a or= time_consuming_func_returning_bool()

to avoid calling the time-consuming function. That would be neat.

Upvotes: 3

Views: 3845

Answers (1)

kabanus
kabanus

Reputation: 25895

Not really. Closest two options I have in mind:

a = a if a else b
a = a or b

Unless I am misunderstanding and you mean bitwise:

a=5  #101
a|=3 #010

result is a==7 (111). Of course |= will work with True and False, but I'm not sure it's considered proper in the language:

a=True
a|=False

works, a will be True. The only concern here is semantic. If the usage is buried in deep code, someone skimming will assume you're using binary operations here - the above methods are more readable when considering logic.

An even bigger caveat, mentioned by @Moberg, is that Boolean operators aren't lazy. Define

def b():
    print("Don't print this!")
    return False

Then

a|=b()

will print the string even though a is True and it doesn't matter what b is. This is because as far as the Boolean operation is concerned, True is just 1, and b can be any number, so it must be evaluated. Using a or b() or a if a else b() will work as expected.

Upvotes: 4

Related Questions