Python's equivalent of Ruby's ||=
Question: 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.


Answer: 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](http://www.rubyinside.com/what-rubys-
double-pipe-or-equals-really-does-5488.html) 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.

