Search code examples
pythonpython-3.xoperatorsoperator-precedence

Set operator precedence


In python, I am unable to understand the operator precedence.

a = set([1, 2, 3])

a|set([4])-set([2])

The above expression returns {1,2,3,4}. However, I thought the operator | shall be executed before - but this doesn't seem like happening.

When I apply parenthesis, it returns me the desired output, i.e. {1,3,4}

  (a|set([4]))-set([2])

So, my question is why is this happening and what is the operator (for set operators like -, |, &, ^, etc) precedence when applying set operations.


Solution

  • python operator precedence rules give priority to - operator and then to bitwise | operator:

    Now we have a set with union, overloaded with |, and difference, oveloaded with -:

    a = set([1, 2, 3])
    
    a|set([4])-set([2])
    

    The question now became: why do the same rules of precedence apply?

    This is because python evaluates operator expressions applying the same rules precedence for all classes that overload the standard operators:

    class Fagiolo:
    
        def __init__(self, val):
            self.val = val
    
        def __or__(self, other):
            return Fagiolo("({}+{})".format(self.val, other.val))
    
        def __sub__(self, other):
            return Fagiolo("({}-{})".format(self.val, other.val))
    
        def __str__(self):
            return self.val
    
    red = Fagiolo("red")
    white = Fagiolo("white")
    
    new_born = red | white - Fagiolo("blue")
    
    print(new_born)
    

    gives:

    (red+(white-blue))