←back to thread

317 points est | 1 comments | | HN request time: 0.221s | 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. misnome ◴[] No.17450465[source]
I know your question isn't specifically about the exact example, but are you aware that they added the @ operator for matmul in 3.5?

I think anything general would probably be considered as cluttering up the grammar or non-pythonic. Completely custom unicode operators was something I loved about Swift (open to abuse, but really useful in moderation).