Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's equivalent of Ruby's ||=

Tags:

python

ruby

To check if a variable exist, and if exits, use the original value, other wise, use the new value assigned. In ruby, it's var ||= var_new

How to write it in python?

PS: I don't know the name of ||=, I simply can't search it in Bing.

like image 448
cqcn1991 Avatar asked Sep 23 '15 02:09

cqcn1991


People also ask

Does Python have symbols like Ruby?

There is no python equivalent for Ruby's symbols.

Does Python have or equals?

Precise answer: No. Python does not have a single built-in operator op that can translate x = x or y into x op y . But, it almost does. The bitwise or-equals operator ( |= ) will function as described above if both operands are being treated as booleans, with a caveat.

What does &= Do python?

It means bitwise AND operation. Example : x = 5 x &= 3 #which is similar to x = x & 3 print(x)


1 Answers

I think there is some confusion from the people who aren't really sure what the conditional assignment operator (||=) does, and also some misunderstanding about how variables are spawned in Ruby.

Everyone should read this article on the subject. A TLDR quote:

A common misconception is that a ||= b is equivalent to a = a || b, but it behaves like a || a = b

In a = a || b, a is set to something by the statement on every run, whereas with a || a = b, a is only set if a is logically false (i.e. if it's nil or false) because || is 'short circuiting'. That is, if the left hand side of the || comparison is true, there's no need to check the right hand side.

And another very important note:

...a variable assignment, even if not run, immediately summons that variable into being.

# Ruby
x = 10 if 2 == 5
puts x

Even though the first line won't be run, x will exist on the second line and no exception will be raised.

This means that Ruby will absolutely ensure that there is a variable container for a value to be placed into before any righthand conditionals take place. ||= doesn't assign if a is not defined, it assigns if a is falsy (again, false or nil - nil being the default nothingness value in Ruby), whilst guaranteeing a is defined.

What does this mean for Python?

Well, if a is defined, the following:

# Ruby
a ||= 10

is actually equivalent to:

# Python
if not a:
    a = 10

while the following:

# Either language
a = a or 10

is close, but it always assigns a value, whereas the previous examples do not.

And if a is not defined the whole operation is closer to:

# Python
a = None
if not a:
    a = 10

Because a very explicit example of what a ||= 10 does when a is not defined would be:

# Ruby
if not defined? a
    a = nil
end

if not a
    a = 10
end

At the end of the day, the ||= operator is not completely translatable to Python in any kind of 'Pythonic' way, because of how it relies on the underlying variable spawning in Ruby.

like image 74
Oka Avatar answered Sep 21 '22 09:09

Oka