Python conditional assignment operator

前端 未结 10 2025
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 18:03

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

Example in Ruby :

 variable_n         


        
10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 18:51

    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')
    

提交回复
热议问题