
Hacking Infix Operators into Python with Decorators - z1mm32m4n
http://tomerfiliba.com/blog/Infix-Operators/
======
p4wnc6
I've used this recipe in my IPython launch script to define SQL-like infix
operators for working with pandas DataFrames. You can see that source here: <
[https://github.com/spearsem/configs/blob/master/ipython_conf...](https://github.com/spearsem/configs/blob/master/ipython_configs/profile_default/launch.py#L397)
>.

You can scroll up a little for some of the other definitions.

This is just toy code of course, but it's fun sometimes to be able to say
something like

SELECT * FROM>> dfrm <<WHERE>> COL('A') < 0.5

for a DataFrame "dfrm" with a column "A"

I like the "<< _ >>" syntax better myself, even though the "|_|" syntax uses
fewer characters.

------
freyrs3
> Ain’t that cool?

Oh it is! Now never use this.

~~~
cranium
Yup. I think it is the alternative definition of a "hack". :)

------
40281889
I wrote something similar a while ago as an experiment. It's a bit amateur-ish
but I had fun doing it.
[https://github.com/sleibrock/Unit.py](https://github.com/sleibrock/Unit.py)

------
hatmatrix
Woudn't it be more interesting to do it the other way around? Make the infix
operator a prefix operator. For instance, in R you can do x+y or "+"(x,y).
Sadly, you can't do "+"(x,y,z) and so on, but you can use it in this way:

    
    
        args = list(x,y)
        do.call("+",args)

~~~
ekimekim
Python has builtin alternate forms of all infix operators in the "operator"
module:

    
    
        from operator import add
        add(x, y)
    

Like in your example, you can't simply give it more args (since infix
operators are binary operators and may not be associative). But you could
combine it with some other builtins like so:

    
    
        from operator import add
        reduce(add, [x, y, z])
    

Of course, for the specific case of addition, you can simply use the builtin
"sum()" function, which is almost equivalent to above (sum() assumes an
initial value of 0 by default, so sum(list) === reduce(add, list, 0))

------
Gratsby
And here I thought that this kind of stuff was the reason people didn't like
perl or haskell.

~~~
foota
The difference being that this would never fly in a python codebase.

------
coleifer
2005: [http://code.activestate.com/recipes/384122-infix-
operators/](http://code.activestate.com/recipes/384122-infix-operators/)

------
Mithaldu
Funny, forced infix in Perl uses the same syntax and mechanics:

[https://metacpan.org/pod/Sub::Infix](https://metacpan.org/pod/Sub::Infix)

------
ak4g
[2012]

------
michel-slm
First paragraph is factually incorrect already, lumping Lisp (prefix) with
Forth (postfix) ...

