pythonpython-3.xsetset-intersectionset-union

Practical Use of Reversed Set Operators in Python


Is there any difference between using the reversed union or intersection operators on sets in Python?

for instance,

s & z corresponds to s.__and__(z)

z & s corresponds to s.__rand__(z)

If these are supposed to return the same thing, why have the reversed operator in the first place? Am I missing something?


Solution

  • set and frozenset follow the number protocol and they don't define the reversed operations explicitly but they get these "for free" because they implement the normal methods (like __and__).

    However reversed operations are particularly useful when dealing with subclasses because if the right operand is a subclass of the left operand the reversed operation is attempted first. But in case of plain sets and frozensets this doesn't make any difference because they don't inherit from each other.

    These reversed operations are also used if the first operand returns NotImplemented in it's __add__. But again this isn't really useful for set and frozenset because they only allow operations with other set-alikes and at least set and frozenset don't return NotImplemented when the other operand is another set.

    Also z & s doesn't correspond to s.__rand__(z), except when s is a subclass of z. Otherwise z.__and__(s) will be attempted before s.__rand__(z).

    So I doubt there are use-cases for the reversed union and intersection but it should explain "why these methods exist".