[Python-ideas] Infix functions

Bruce Leban bruce at leapyear.org
Sun Feb 23 04:17:50 CET 2014


On Sat, Feb 22, 2014 at 5:23 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> For example, I'd like to use
> ∪ and ∩ for set union and intersection, but instead those two operations
> get mapped to & and | and I can never remember which is which. I'd like
> to use operators such as ⊕ ⊗. But so long as Python operators are ASCII
> only, that cannot happen.
>

What if Python didn't restrict you to ASCII operators? Here's specifics of
how that could work:

(1) An extended operator is a *single* math symbol character, e.g., ∩ or ⊕or
⊲ but not ⊲⊲. The set of allowed characters needs to be defined carefully.
It could be any Unicode S-class character with the math property. Extended
operators can be combined with an equal sign to do in-place updating,
e.g., A ∩=
B.

(2) Extended operators can be declared like this.

class sample:
    def '∩'(self, rhs):

        return self.value.intersection(sample.get_set(rhs))


    def 'r∩'(self, lhs):

        """Reversed operator."""
        return sample.get_set(lhs).intersection(self.value)


    def 'i∩'(self, rhs):

        self.value.intersection_update(sample.get_set(rhs))

    @staticmethod
    def get_set(self):
        try:
            value = rhs.value
        except AttributeError:

       value = rhs

   return set(value)





I'm not sure about enclosing the operator character in quotes. C++ and C#
use an operator keyword, while Ruby doesn't mark it at all. Python, of
course, uses __oper__ functions for overloading built-in operators. Writing
__∩__ would complicate the tokenizer as it would have to recognize this
exact syntax and treat it as an identifier while not allowing math symbol
characters in other uses in an identifier. And I probably need to write
sample['∩'] not sample.∩. Without the quotes or something along those
lines, these look too similar:

def U(a, b): pass
def ∪(a, b): pass


(3) All extended operators have the same precedence, between comparisons
and bitwise or. Perhaps expressions mixing different extended operators
always require parentheses, i.e., (A ∪ B ∩ C) would be a syntax error.

To my mind this is way more readable than something like *%+& which looks
like someone cursing. :-)

--- Bruce
Learn how hackers think: http://j.mp/gruyere-security
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140222/4714911e/attachment-0001.html>


More information about the Python-ideas mailing list