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'
No, the replacement is:
try:
v
except NameError:
v = 'bla bla'
However, wanting to use this construct is a sign of overly complicated code flow. Usually, you'd do the following:
try:
v = complicated()
except ComplicatedError: # complicated failed
v = 'fallback value'
and never be unsure whether v
is set or not. If it's one of many options that can either be set or not, use a dictionary and its get
method which allows a default value.
这篇关于Python 条件赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!