Python conditional assignment operator

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

    I would use

    x = 'default' if not x else x
    

    Much shorter than all of your alternatives suggested here, and straight to the point. Read, "set x to 'default' if x is not set otherwise keep it as x." If you need None, 0, False, or "" to be valid values however, you will need to change this behavior, for instance:

    valid_vals = ("", 0, False) # We want None to be the only un-set value
    
    x = 'default' if not x and x not in valid_vals else x
    

    This sort of thing is also just begging to be turned into a function you can use everywhere easily:

    setval_if = lambda val: 'default' if not val and val not in valid_vals else val
    

    at which point, you can use it as:

    >>> x = None # To set it to something not valid
    >>> x = setval_if(x) # Using our special function is short and sweet now!
    >>> print x # Let's check to make sure our None valued variable actually got set
    'default'
    

    Finally, if you are really missing your Ruby infix notation, you could overload ||=| (or something similar) by following this guy's hack: http://code.activestate.com/recipes/384122-infix-operators/

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

    No, there is no nonsense like that. Something we have not missed in Python for 20 years.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 19:08

    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.

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