Python conditional assignment operator

前端 未结 10 1976
没有蜡笔的小新
没有蜡笔的小新 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:57

    (can't comment or I would just do that) I believe the suggestion to check locals above is not quite right. It should be:

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

    to be correct in all contexts.

    However, despite its upvotes, I don't think even that is a good analog to the Ruby operator. Since the Ruby operator allows more than just a simple name on the left:

    foo[12] ||= something
    foo.bar ||= something
    

    The exception method is probably closest analog.

提交回复
热议问题