←back to thread

317 points est | 1 comments | | HN request time: 0.211s | source
Show context
jkabrg ◴[] No.17450249[source]
It would be nice if in Python you could define new operators instead of overloading existing ones. It would make matrix multiplication look nicer.

I'm thinking it could look like this:

  import numpy as np
  
  def M1 %*% M2 with same precedence as *:
    return M1.matmul(M2)

  foo_matrix = np.matrix([[1,1],[1,1]])
  bar_matrix = np.matrix([[2,2],[2,2]])
  print(foo_matrix %*% bar_matrix)
Also, it would be nice to have a pipe operator `%>%` such that

  foo %>% f()
is equivalent to

  f(foo)
The alternative is to make f a method of foo, and then you can write

  foo.f()
But what happens if I don't want f to be a method? I just want the style of writing the f after the foo, but I don't want the baggage of OOP. Is that anti-Pythonic?
replies(6): >>17450465 #>>17450468 #>>17450486 #>>17451059 #>>17451069 #>>17452494 #
1. ASalazarMX ◴[] No.17451059[source]
Why not a repipe gluing operator so that

    foo%$%bar %>%>% f()
is equivalent to

    (f(foo(bar)), f(bar(foo)))
I'm just kidding, but please no more cryptic symbols in Python's syntax, if it can be solved with functions instead. We have other languages to scratch that itch.

I haven't read the PEP, so I don't know the trade-offs, but I'm not loving this (:=) syntactic sugar either.