I am quite new to the Python world, so please excuse my dumb question.
In a number of circumstances, I implement a functions that works on array-like numerical inputs, and it is usually advantageous to make use of NumPy utilities for basic operations on the sequences. To this end, I would write something like this:
import numpy as np
def f(x):
if not isinstance(x, np.ndarray):
x = np.asarray(x)
# and from now on we know that x is a NumPy array, with all standard methods
(Note that I don't want to rely on the caller to always pass NumPy arrays.)
I was wondering what would be the additional overhead if simplified the code by removing the if
? I.e., having something like
def f(x):
x = np.asarray(x)
# and from now on we know that x is a NumPy array, with all standard methods
Basically, the difference between two cases is that second code is more compact, but will unnecessarily call np.asarray
even if x
is already a NumPy array.