Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does |= (pipe equal) sign do in python?

Tags:

I saw a piece of code in a project where following is written:

 move = Move.create({     'name': repair.name,     'product_id': repair.product_id.id,     'product_uom': repair.product_uom.id or repair.product_id.uom_id.id,     'product_uom_qty': repair.product_qty,     'partner_id': repair.address_id.id,     'location_id': repair.location_id.id,     'location_dest_id': repair.location_dest_id.id,     'restrict_lot_id': repair.lot_id.id, }) moves |= move moves.action_done() 

What does the |= meaning here?

like image 720
Tanzil Khan Avatar asked Oct 26 '16 05:10

Tanzil Khan


People also ask

What does |= mean in Python?

|= on Booleans The Python |= operator when applied to two Boolean values A and B performs the logical OR operation A | B and assigns the result to the first operand A . As a result, operand A is False if both A and B are False and True otherwise.

What does |= mean in coding?

The bitwise OR assignment operator ( |= ) uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.

What does pipe symbol do in Python?

Pipe is a Python library that enables you to use pipes in Python. A pipe ( | ) passes the results of one method to another method. I like Pipe because it makes my code look cleaner when applying multiple methods to a Python iterable. Since Pipe only provides a few methods, it is also very easy to learn Pipe.

What is meaning of |= in C#?

In general: |= will only ever add bits to the target. &= will only ever remove bits from the target.


2 Answers

It's a compound operator, when you say: x |= y it's equivalent to x = x | y

The | operator means bitwise or and it operates on integers at the bit-by-bit level, here is an example:

a = 3    #                (011)          #                 ||| b = 4    #                (100)          #                 ||| a |= b   #<-- a is now 7  (111) 

Another example:

a = 2    #                (10)          #                 || b = 2    #                (10)          #                 || a |= b   #<-- a is now 2  (10) 

So each bit in the result will be set if that same bit is set in either of the two sources and zero if both of the two sources has a zero in that bit.

The pipe is also used on sets to get the union:

a = {1,2,3} b = {2,3,4} c = {4,5,6} print(a | b | c)  # <--- {1, 2, 3, 4, 5, 6} 
like image 115
Bilal Avatar answered Nov 16 '22 19:11

Bilal


As @AChampion already mentioned in the first question comment, it could be "bitwise or" or "set union". While this question has Odoo as context, it is "set union" for the Odoo class RecordSet.

This class was introduced with the new API on Odoo 8. For other operators look into the official doc of Odoo.

like image 33
CZoellner Avatar answered Nov 16 '22 21:11

CZoellner