@ is for matmul/inner, what's for the outer product?

In Python, the @ operator relays to the __matmul__ property of an element. This comes in handy when implementing a method that stays agnostic of the actual backend. For example

def inner(x, y):
    return x @ y
    # same:
    # return x.__matmul__(y)

implements an inner product, for x, y being numpy arrays or any other fancy array class.

Is there a similar such API for the outer product, too?


Solution 1:

The @ operator was added as PEP 465 for __matmul__. There is no such thing (and no dunder method) for the outer product.

In fact, the outer product is a simple multiplication (*) once the first array got reshaped:

import numpy as np

a = np.array([1,2,3])
b = np.array([10, 100])

np.outer(a, b)

a[:,None] * b

Output of both products:

array([[ 10, 100],
       [ 20, 200],
       [ 30, 300]])