Infix function in python

So did I, until I realised that this was actually a really REALLY bad idea. (It’s not the same language if any two programs can have completely different syntax and behaviour, it’s a family of languages - and none of them will be particularly good.) Though I don’t regret having done it. It was a good exercise, planning out a language like that, and in the process, learning what’s actually important. There was never an interpreter or even parser for it, just a specification, and that was enough for me to permanently shelve it :slight_smile:

Yeah, that IS an option. IMO it sucks though. Precedence is a huge benefit. In my one, every user-defined operator had a precedence/associativity number, higher numbers have higher precedence, and odd/even determining left/right associative. And it still sucked :slight_smile:

Designing a DSL from scratch is actually a lot of fun. It’s really fascinating which parts are easy and which parts are hard. I designed a DSL for my Twitch channel bot in 50 lines of LR(1) grammar… and then to make the “else” clause optional on an “if” statement took another 47 lines of grammar. xkcd: Tasks

When I say “user defined” it’s not like I expected everyone to
define their own arithmetic operators. There would have been a
standard prelude that most programs would use. It was more of an
exercise in keeping the compiler extremely simple.

Also I didn’t expect anyone other than me would ever use it. :slight_smile:

1 Like

Yeah, with mine, the plan was to have some sort of import stdoperators directive that would pull in all the basic arithmetic operators, but that from the language’s point of view, they would still all just be defined in code.

I didn’t even expect me to use it :slight_smile:

1 Like

I never wrote a programming language before, but it’s not clear to me why the precedence of the + - operators is difficult:

1 - 2 + 3

should always be processed as

((1 - 2) + 3)

It’s not. It’s also not USUALLY a problem when multiplication and division are brought in. However, what about all the other operators? Where do bitwise and comparison operators come in? And the ternary conditional operator (truthy if cond else falsy in Python, cond ? truthy : falsy in C-inspired languages) - does it bind more tightly to the left or to the right? Okay, to be fair, no sane language has ever disagreed on that last one. And even PHP came around eventually and fixed it. But still, there’s a lot of complexity in operator precedence, and it usually has to be designed in, not done arbitrarily as a coincidence of implementation.

1 Like

Ah ok, I thought it was a problem only involving + -

Yeah this gives devs the ability to create words like “and” and “or” in Python, dropping them from the reserved keywords status.

Wouldn’t revive this myself, but as we are here…

This is one part of the problem. I tried using infix operators. The idea is great, but in practice they feel clumsy. Ended up never using them anywhere. Neither I have seen anyone else actually using them in any respectable place - just few implementations so that users can play around.

Well, could just make use of what we have. Precedence levels already exist.
Can just name/number them so that user can assign his implemented operator to one of the groups.

This way, can either define completely separate DSL or just add couple more into the mix.


So although I think none of the mentioned are hard problems, but I don’t think “polluting” Python with this is a good idea.

Nevertheless, ability to devise DSLs can indeed be useful. Thus the only path that I can see is some sort of “encapsulated DSL context”. E.g.:

dsl MyDsl:
    def union_of_stuff('∪', a, b, precedence='same as +-'):
        if type(a) is int:
            a = {a}
        if type(b) is int:
            b = {b}
        return a.union(b)

using MyDsl:
    union = 1 ∪ {2, 3} - 2    # same precedence: ∪, -

print(union)    # {1, 3}

But this is non-trivial design work, would need to take ongoing MACROs trend into consideration and many other things.

Quick clarification: The operator used here is not the letter U, but the Unicode character “UNION” U+222A. Possibly not the clearest choice for an example, due to this confusion. In any case, the use of non-alphabetics is almost certainly necessary when creating new operators, as they are otherwise invalid in this sort of context.

2 Likes

Not sure what do you mean with “devs”. I suppose with mean Python core devs. I’m quite sure this will never happen, luckily ;-)

1 Like

What if I write:

dsl MyDsl:
    def new_plus('+', a, b, precedence='same as +-'):
        return a - b

That was just a rough depiction.
That is neither API I would propose, nor is a concept that is subject to scrutiny.

Nevertheless, choices / decisions would need to be made to overcome such issues and this one might be a fairly easy one - either allow overriding existing operators or not.

I am not advocating for this, just think that it is achievable. What would be good is to have some example applications that would shine a light on “how amazing it would be to have this”. Personally, I have none.

1 Like

And that’s the point. What if ∪ is added to Python as operator?

I am not following what you are getting at.

Declaring precedence of operators when you define them sounds like a
good idea, but it would be problematic in Python. The precedence needs
to be known at compile time, but the compiler currently doesn’t know
anything about imported modules, and there would be difficulties in
making it do so.

1 Like

It’s simple.

You proposed to add a way to define new operators, for example ∪, that can be used only in a context. You also said that Python should consider if these new operators can override existing operators.

So, this is the scenario. You create a library with the new ∪ operator. This library became very popular. At some point, Python decide to introduce the ∪ operator in the language. They could decide to:

  1. follow completely your design of the ∪ operator
  2. deviate in some way from your design, or use it for a totally different operation

In case 1, there’s no problem. But if Python devs would choose case 2, there are 2 subcases:

A. Python devs decide user defined operators can override existing operators
B. Python devs decide user defined operators cannot override existing operators

If B will be chosen, it’s a big problem. All the existing code that used the ∪ will not work anymore or they will fail in some bizarre situations.

So probably Python dev will choose A. But if A is chosen, one can also override already existing operators, like +. For example, I could do:

dsl MyDsl:
    def new_plus('+', a, b, precedence='same as +-'):
        if isinstance(a, str):
                return a + str(b)

        if isinstance(b, str):
                return str(a) + b

        return a + b

so the sum with a string with a non-string will do an implicit cast to string of the non-string object and concatenate the two strings, as Java do.

Furthermore, why limiting to infix operators?

dsl MyDsl:
    def plus_plus_postfix('++', a, None, precedence='boh'):
        b = a
        a += 1
        return b

    def plus_plus_prefix('++', None, a, precedence='boh'):
        a += 1
        return a
2 Likes

It isn’t at compile time, but at parsing time, that the operator precedence is determined according to the grammar rules.

In the broad dichotomy of compile-time vs run-time, parsing happens at compile-time. The point is that Python cannot use any information from imported modules as part of the compilation process, including lexing and parsing.

In fact, Python cannot even know that new operators have been defined. The proposed new syntax using MyDsl would need to be similar to, but completely different than, an import. It would need to find the MyDsl.py file at compile time in order to work properly. This is an even large change to Python than it first seems.

9 Likes

I didn’t propose new syntax, that was just a rough depiction of what I meant by “DSL context”.


I think this is just another thread that leads back to PEP 638 – Syntactic Macros | peps.python.org.
It looks like a potential feature of it.
At the very least it needs to be considered in the same context.

I don’t see the problem. I’m glad Python does not implicitly concatenate strings [cast ints to string when concatenating with a string]. But why should I care about stopping someone who wants to override the + operator in their code? Why should you?

I do understand that you shouldn’t make bad code too enticing, but I think this first example would be so obviously bad, it’d never get merged into a code repository I need to care about.
++ is unique enough that on the balance of probability, I think in a situation where I’d encounter it it would probably be justified.


edit: fixed an inaccuracy in the words I used, because @jobe cared enough to correct me.

2 Likes