Python conditional assignment operator

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

    I am not sure I understand the question properly here ... Trying to "read" the value of an "undefined" variable name will trigger a NameError. (see here, that Python has "names", not variables...).

    == EDIT ==

    As pointed out in the comments by delnan, the code below is not robust and will break in numerous situations ...

    Nevertheless, if your variable "exists", but has some sort of dummy value, like None, the following would work :

    >>> my_possibly_None_value = None
    >>> myval = my_possibly_None_value or 5
    >>> myval
    5
    >>> my_possibly_None_value = 12
    >>> myval = my_possibly_None_value or 5
    >>> myval
    12
    >>> 
    

    (see this paragraph about Truth Values)

提交回复
热议问题