What is the difference between type and dtype?

3

Based on a previous question , I saw that it is possible to identify a variable using type . For example:

print(type(3.1415).__name__) #retorno >> float

Doing some research, I saw that dtype exists. What is the difference between type and dtype ? In what situation should I use dtype ?

    
asked by anonymous 23.03.2017 / 17:29

1 answer

3

type is a built-in name of the Python language - it is a call that either identifies the type of an object, or creates a new type.

dtype is the name of a parameter / member of numerical numpy library objects. Although numpy is very popular, it can not be confused with the language core - nor dtype is universal - even in numpy it is an attribute or parameter that will only be present where it makes sense.

dtype is the abbreviation for data type and is used in numpy and related numeric / scientific biblioitoecas to identify the type of data that will be contained in an object.

This type of data makes sense for numeric calculation and may or may not have a direct match to a native Python data type.

For example, a variable x = 1 has a number in Python, type(x) will return you "int". But there is no dtype(x) or x.dtype . Now:

import numpy as np

y = np.zeros((1000,))

allows y.dtype to be made and the default response is "float64" - which indicates that each number inside the "y" array is a 64-bit floating point number. Being able to specify the dtype in the case of numpy structures allows the developer to have control over the data type and memory consumption with which it is working - could be "float32", for less precision and consumption half of the memory, could be "uint8" if your problem involves black and white images and all the data has only one byte.

Already in the core Python language, due to the dynamic nature, it does not make sense to drill down how a number will be stored. In python3, for example, the language dynamically determines whether the value of an object of type "int" will be an integer native to the machine, or maintained as a string that allows an indeterminate number of decimal places - and who is using the number and will not know.

In addition, it should be added that the data types identified by the "dtype" are strings, which are used as constants - whereas those returned by the "type" are always Python classes. (A class has the __name__ attribute that you used in the question - returns the class name as a string)

    
23.03.2017 / 18:07