Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python conditional assignment operator

Does a Python equivalent to the Ruby ||= operator ("set the variable if the variable is not set") exist?

Example in Ruby :

 variable_not_set ||= 'bla bla'  variable_not_set == 'bla bla'   variable_set = 'pi pi'  variable_set ||= 'bla bla'  variable_set == 'pi pi' 
like image 395
Hartator Avatar asked Jun 19 '11 12:06

Hartator


People also ask

Can we use assignment operator in if condition in Python?

No. Assignment in Python is a statement, not an expression.

What does := mean in Python?

Assignment expressions There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.

Does Python have ternary operator?

The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.


1 Answers

I'm surprised no one offered this answer. It's not as "built-in" as Ruby's ||= but it's basically equivalent and still a one-liner:

foo = foo if 'foo' in locals() else 'default' 

Of course, locals() is just a dictionary, so you can do:

foo = locals().get('foo', 'default') 
like image 160
Keith Devens Avatar answered Oct 16 '22 12:10

Keith Devens