[Numpy-discussion] What is the pythonic way to write a function that handles arrays and scalars?

Joe solarjoe at posteo.org
Tue Dec 12 14:50:14 EST 2017


the best example I found was this one:


def func_for_scalars_or_vectors(x):
     x = np.asarray(x)
     scalar_input = False
     if x.ndim == 0:
         x = x[None]  # Makes x 1D
         scalar_input = True

     # The magic happens here

     if scalar_input:
         return np.squeeze(ret)
     return ret

Is this as good as it gets or do you have other suggestions?


More information about the NumPy-Discussion mailing list