Home > Software engineering >  Python function to convert type if not given type else do nothing
Python function to convert type if not given type else do nothing

Time:08-05

I have multiple variables getting converted to numpy.array. so the input variable may be already numpy.array or a list. But I want to avoid creating multiple isinstance checks to convert .

Any builtin function which type casts if not already the type else does nothing. (Like a ternary operator or a null checking (var or defaultval) )

Or in other words simply converting to same type has any effect in python?

CodePudding user response:

This is what numpy.asarray() is for: if it is passed an array it will return it. You can safely call this on your "maybe arrays", and it will be a no-op:

>>> import numpy as np
... arr = np.arange(3)
... np.asarray(arr) is arr
True

On the other hand if you pass in a list or other sequence, it will be converted to a numpy array. And if you also want to allow numpy ndarray subclasses to be preserved, use np.asanyarray().

  • Related