I have a function that takes the argument NBins
. I want to make a call to this function with a scalar 50
or an array [0, 10, 20, 30]
.
You can check data type of variable.
N = [2,3,5]
P = 5
type(P)
It will give you out put as data type of P.
<type 'int'>
So that you can differentiate that it is an integer or an array.
Previous answers assume that the array is a python standard list. As someone who uses numpy often, I'd recommend a very pythonic test of:
if hasattr(N, "__len__")
Here is the best approach I have found: Check existence of __len__
and __getitem__
.
You may ask why? The reasons includes:
isinstance(obj, abc.Sequence)
fails on some objects including PyTorch's Tensor because they do not implement __contains__
.__len__
and __getitem__
which I feel are minimal methods for array-like objects.So without further ado:
def is_array_like(obj, string_is_array=False, tuple_is_array=True):
result = hasattr(obj, "__len__") and hasattr(obj, '__getitem__')
if result and not string_is_array and isinstance(obj, (str, abc.ByteString)):
result = False
if result and not tuple_is_array and isinstance(obj, tuple):
result = False
return result
Note that I've added default parameters because most of the time you might want to consider strings as values, not arrays. Similarly for tuples.
While, @jamylak's approach is the better one, here is an alternative approach
>>> N=[2,3,5]
>>> P = 5
>>> type(P) in (tuple, list)
False
>>> type(N) in (tuple, list)
True
Another alternative approach (use of class name property):
N = [2,3,5]
P = 5
type(N).__name__ == 'list'
True
type(P).__name__ == 'int'
True
type(N).__name__ in ('list', 'tuple')
True
No need to import anything.
Is there an equivalent to isscalar() in numpy? Yes.
>>> np.isscalar(3.1)
True
>>> np.isscalar([3.1])
False
>>> np.isscalar(False)
True