Python function to convert type if not given type else do nothing

Question:

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?

Asked By: sjd

||

Answers:

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().

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.