Python 在 Ruby 中是否有像 ||= 这样的“或等于”函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3929433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:23:34  来源:igfitidea点击:

Does Python have an "or equals" function like ||= in Ruby?

pythonruby

提问by Sean W.

If not, what is the best way to do this?

如果不是,那么最好的方法是什么?

Right now I'm doing (for a django project):

现在我正在做(对于 django 项目):

if not 'thing_for_purpose' in request.session:
    request.session['thing_for_purpose'] = 5

but its pretty awkward. In Ruby it would be:

但它很尴尬。在 Ruby 中,它将是:

request.session['thing_for_purpose'] ||= 5

which is much nicer.

这是更好的。

采纳答案by Joseph Sheedy

The accepted answer is good for dicts, but the title seeks a general equivalent to Ruby's ||= operator. A common way to do something like ||= in Python is

接受的答案适用于 dicts,但标题寻求与 Ruby 的 ||= 运算符的一般等效项。在 Python 中执行 ||= 之类的常用方法是

x = x or new_value

回答by Jon-Eric

dicthas setdefault().

dictsetdefault().

So if request.sessionis a dict:

所以如果request.sessiondict

request.session.setdefault('thing_for_purpose', 5)

回答by Brian Hicks

Setting a default makes sense if you're doing it in a middleware or something, but if you need a default value in the context of one request:

如果您在中间件或其他东西中设置默认值是有意义的,但如果您需要在一个请求的上下文中使用默认值:

request.session.get('thing_for_purpose', 5) # gets a default

bonus: here's how to really do an ||=in Python.

奖励:这是||=在 Python 中真正执行操作的方法。

def test_function(self, d=None):
    'a simple test function'
    d = d or {}

    # ... do things with d and return ...

回答by curtissv

In general, you can use dict[key] = dict.get(key, 0) + val.

一般来说,您可以使用dict[key] = dict.get(key, 0) + val.

回答by Apollys supports Monica

Precise answer: No.Python does not have a single built-in operator opthat can translate x = x or yinto x op y.

准确答案:不可以。Python 没有一个内置运算符op可以转换x = x or yx op y.

But, it almost does.The bitwise or-equals operator (|=) willfunction as described above if both operands are being treated as booleans, with a caveat. (What's the caveat? Answer is below of course.)

但是,几乎可以。如果两个操作数都被视为布尔值, 按位或等于运算符 ( |=)将按上述方式运行,但需要注意。(有什么警告?答案当然在下面。)

First, the basic demonstration of functionality:

一、功能基本演示:

x = True
x    
Out[141]: True

x |= True
x    
Out[142]: True

x |= False
x    
Out[143]: True

x &= False
x    
Out[144]: False

x &= True
x    
Out[145]: False

x |= False
x    
Out[146]: False

x |= True
x   
Out[147]: True

The caveat is due python not being strictly-typed, and thus even if the values are being treated as booleans in an expression they will not be short-circuited if given to a bitwise operator. For example, suppose we had a boolean function which clears a list and returns Trueiff there were elements deleted:

警告是由于 python 不是严格类型的,因此即使在表达式中将值视为布尔值,如果将它们提供给按位运算符,它们也不会短路。例如,假设我们有一个布尔函数,它清除列表并True在删除元素时返回:

def  my_clear_list(lst):
    if not lst:
        return False
    else:
        del lst[:]
        return True

Now we can see the short-circuited behavior as so:

现在我们可以看到短路行为如下:

x = True
lst = [1, 2, 3]
x = x or my_clear_list(lst)
print(x, lst)

Output: True [1, 2, 3]

However, switching the orto a bitwise or (|) removes the short-circuit, so the function my_clear_listexecutes.

但是,将 切换or为按位或 ( |) 会消除短路,因此函数会my_clear_list执行。

x = True
lst = [1, 2, 3]
x = x | my_clear_list(lst)
print(x, lst)

Output: True []

Above, x = x | my_clear_list(lst)is equivalent to x |= my_clear_list(lst).

以上,x = x | my_clear_list(lst)相当于x |= my_clear_list(lst)