pythonsyntax-rules

What does the “|” sign mean in Python?


This question originally asked (wrongly) what does "|" mean in Python, when the actual question was about Django. That question had a wonderful answer by Triptych I want to preserve.


Solution

  • In Python, the '|' operator is defined by default on integer types and set types.

    If the two operands are integers, then it will perform a bitwise or, which is a mathematical operation.

    If the two operands are set types, the '|' operator will return the union of two sets.

    a = set([1,2,3])
    b = set([2,3,4])
    c = a|b  # = set([1,2,3,4])
    

    Additionally, authors may define operator behavior for custom types, so if something.property is a user-defined object, you should check that class definition for an __or__() method, which will then define the behavior in your code sample.

    So, it's impossible to give you a precise answer without knowing the data types for the two operands, but usually it will be a bitwise or.