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

时间:2022-06-30 11:57:12

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.

这是好得多。

5 个解决方案

#1


137  

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

#2


14  

dict has setdefault().

dict setdefault()。

So if request.session is a dict:

如果请求。会话是一个东西:

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

#3


9  

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 ...

#4


2  

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

精确的答案:没有。Python没有一个内置的操作符op,可以将x = x或y转换为x op y。

But, it almost does. The bitwise or-equals operator (|=) will function 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 True iff there were elements deleted:

需要注意的是,python并不是严格类型的,因此即使将值作为布尔值处理,也不会在给定一个位运算符时发生短路。例如,假设我们有一个布尔函数,它清除一个列表并返回True iff,有一些元素被删除:

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 or to a bitwise or (|) removes the short-circuit, so the function my_clear_list executes.

但是,将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)。

#5


0  

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

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

#1


137  

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

#2


14  

dict has setdefault().

dict setdefault()。

So if request.session is a dict:

如果请求。会话是一个东西:

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

#3


9  

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 ...

#4


2  

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

精确的答案:没有。Python没有一个内置的操作符op,可以将x = x或y转换为x op y。

But, it almost does. The bitwise or-equals operator (|=) will function 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 True iff there were elements deleted:

需要注意的是,python并不是严格类型的,因此即使将值作为布尔值处理,也不会在给定一个位运算符时发生短路。例如,假设我们有一个布尔函数,它清除一个列表并返回True iff,有一些元素被删除:

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 or to a bitwise or (|) removes the short-circuit, so the function my_clear_list executes.

但是,将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)。

#5


0  

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

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