Why does np.vectorize promotes np.uint8 elements of a 1-d array to int, but leaves types of list elements unchanged?

22 hours ago 1
ARTICLE AD BOX

I have this Python function:

import numpy as np def f(x): print(f"x is {x} and has type {type(x)}") try: print(f"x.dtype is {x.dtype}") except AttributeError: print("no dtype exists on x") return x

It takes a value, informs us of its type and its .dtype attribute, or lack of such, and then returns the value.

I wrap it using np.vectorize. I call:

res = np.vectorize(f)(np.array([np.uint8(1)])) # res will be: array([1], dtype=uint8)

This call prints:

x is 1 and has type <class 'numpy.uint8'> x.dtype is uint8 x is 1 and has type <class 'int'> no dtype exists on x

I understand the first two lines. Before actually executing the function for every element of the input array, ie np.array([np.uint8(1)]), it takes the first element of it (ie np.uint8(1)), runs the function to check the output type and size. More info in this thread or in the docs.

After having run the function for the first element, it iterates over all elements. So, it takes the first element again. My surprise is that now the first element is an int, not a numpy.uint8 value, as per the third line of the above print. (This one: x is 1 and has type <class 'int'>).

Of course, no dtype exists on an int, because its not a numpy dtype, but a Python scalar (that's why the 4th line is no dtype exists on x).

This behaviour does not happen when the input np.uint8(1) is not the element of a np.array([]), but is a list or not even an iterable. These two lines below:

res = np.vectorize(f)([np.uint8(1)]) # res: array([1], dtype=uint8) res = np.vectorize(f)(np.uint8(1)) # res: array(1, dtype=uint8)

both result in these prints:

x is 1 and has type <class 'numpy.uint8'> x.dtype is uint8 x is 1 and has type <class 'numpy.uint8'> x.dtype is uint8

The third line is remarkably different compared to the case above.

Why does np.vectorize promotes np.uint8 elements of a 1-d array to int, but leaves types of list elements unchanged?

Read Entire Article