Pipe character in Python

PythonPipeBitwise Operators

Python Problem Overview


I see a "pipe" character (|) used in a function call:

res = c1.create(go, come, swim, "", startTime, endTime, "OK", ax|bx)

What is the meaning of the pipe in ax|bx?

Python Solutions


Solution 1 - Python

This is also the union set operator

set([1,2]) | set([2,3])

This will result in set([1, 2, 3])

Solution 2 - Python

It is a bitwise OR of integers. For example, if one or both of ax or bx are 1, this evaluates to 1, otherwise to 0. It also works on other integers, for example 15 | 128 = 143, i.e. 00001111 | 10000000 = 10001111 in binary.

Solution 3 - Python

Yep, all answers above are correct.

Although you could find more exotic use cases for "|", if it is an overloaded operator used by a class, for example,

https://github.com/twitter/pycascading/wiki#pycascading

input = flow.source(Hfs(TextLine(), 'input_file.txt'))
output = flow.sink(Hfs(TextDelimited(), 'output_folder'))

input | map_replace(split_words, 'word') | group_by('word', native.count()) | output

In this specific use case pipe "|" operator can be better thought as a unix pipe operator. But I agree, bit-wise operator and union set operator are much more common use cases for "|" in Python.

Solution 4 - Python

In Python 3.9 - PEP 584 - Add Union Operators To dict in the section titled Specification, the operator is explained. The pipe was enhanced to merge (union) dictionaries.

>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 4, 'nut': 5}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 4, 'nut': 5} # comment 1
>>> e | d
{'cheese': 3, 'nut': 5, 'spam': 1, 'eggs': 2} # comment 2

comment 1 If a key appears in both operands, the last-seen value (i.e. that from the right-hand operand) wins --> 'cheese': 4 instead of 'cheese': 3

comment 2 cheese appears twice, the second value is selected so d[cheese]=3

Solution 5 - Python

Solution 6 - Python

It is a bitwise-or.

The documentation for all operators in Python can be found in the Index - Symbols page of the Python documentation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalwbtcView Question on Stackoverflow
Solution 1 - Pythongui11aumeView Answer on Stackoverflow
Solution 2 - Pythonahmet alp balkanView Answer on Stackoverflow
Solution 3 - PythonTagarView Answer on Stackoverflow
Solution 4 - Pythonuser12989841View Answer on Stackoverflow
Solution 5 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 6 - PythontzotView Answer on Stackoverflow