Home > Blockchain >  Why do we use array_name.dtype versus dtype(array_name) in python, numpy
Why do we use array_name.dtype versus dtype(array_name) in python, numpy

Time:11-21

In numpy, to check the type of array the code is

type(array_name)

but to check the type of the values stored in the array the code is

array_name.dtype

I would have thought it would be

dtype(array_name)

This problem keeps arises in different contexts as well.

CodePudding user response:

In Python, type is a built-in function that returns the type of anything you pass to it in argument. You could call type(x) without any assumption on x and Python would tell you about the type of x.

On the other hand, numpy arrays are objects. As such they have a certain number of attributes and one of them is dtype. Only numpy arrays (and other objects that follow the same logic) have dtypes: it wouldn't make sense to ask for the dtype of an integer for example.

CodePudding user response:

dtype is the type of the contents of the array, and it's a numpy (and pandas)-specific thing. It's easier and more convenient both for the developers and the users of the library to store it as such.

type returns the Python type of any object, is a Python built-in function. While the designers of Python could have made it a property on every object, they chose to make it a global function.

dtype and type seem very similar in this case, but in reality, they have nothing to do with each other.

  • Related