Tanzil Khan
Tanzil Khan

Reputation: 970

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

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?

Upvotes: 25

Views: 16442

Answers (4)

Stephen
Stephen

Reputation: 8858

In addition to the meanings that others have pointed out, beginning in Python 3.9 my_dict |= another_dict means to take the entries in another_dict and add them to my_dict, overwriting any duplicates.

Or as the documentation says (make sure you're looking at the entry under dict and not under set):

d |= other

Update the dictionary d with keys and values from other, which may be either a mapping or an iterable of key/value pairs. The values of other take priority when d and other share keys.

Upvotes: 0

CZoellner
CZoellner

Reputation: 14801

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.

For your example: It's the same as moves = moves | move and means a union of moves and move.

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

Upvotes: 9

Bilal
Bilal

Reputation: 3282

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}

Upvotes: 15

Mehran BaghGolshani
Mehran BaghGolshani

Reputation: 35

It simply means moves = move | moves.

Upvotes: -2

Related Questions