Python conditional assignment operator

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

    I think what you are looking for, if you are looking for something in a dictionary, is the setdefault method:

    (Pdb) we=dict()
    (Pdb) we.setdefault('e',14)
    14
    (Pdb) we['e']
    14
    (Pdb) we['r']="p"
    (Pdb) we.setdefault('r','jeff')
    'p'
    (Pdb) we['r']
    'p'
    (Pdb) we[e]
    *** NameError: name 'e' is not defined
    (Pdb) we['e']
    14
    (Pdb) we['q2']
    

    *** KeyError: 'q2' (Pdb)

    The important thing to note in my example is that the setdefault method changes the dictionary if and only if the key that the setdefault method refers to is not present.

    0 讨论(0)
  • 2020-12-08 18:44

    No, not knowing which variables are defined is a bug, not a feature in Python.

    Use dicts instead:

    d = {}
    d.setdefault('key', 1)
    d['key'] == 1
    
    d['key'] = 2
    d.setdefault('key', 1)
    d['key'] == 2
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 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')
    
    0 讨论(0)
  • 2020-12-08 18:51

    I usually do this the following way:

    def set_if_not_exists(obj,attr,value):
     if not hasattr(obj,attr): setattr(obj,attr,value)
    
    0 讨论(0)
  • 2020-12-08 18:54

    There is conditional assignment in Python 2.5 and later - the syntax is not very obvious hence it's easy to miss. Here's how you do it:

    x = true_value if condition else false_value
    

    For further reference, check out the Python 2.5 docs.

    0 讨论(0)
提交回复
热议问题