I'm writing a type checker for a function which needs to check if an argument is of type <class 'numpy.ndarray'>. However, if v
is a NumPy array, checking if type(v) == np.array
eventually depends on how one globally imports numpy
.
For example if import numpy
is solely used, then the type checker can't run as type(v) == np.array
returns an undefined np
error. Is there any way to get around how one might import numpy yet still check if something is of a numpy type?
CodePudding user response:
Convert the output of type
to string and check if it's "<class 'numpy.ndarray'>"
This works:
import numpy
v = numpy.array([1.])
print(str(type(v)) == "<class 'numpy.ndarray'>")
And this too:
import numpy as np
v = np.array([1.])
print(str(type(v)) == "<class 'numpy.ndarray'>")