What is the difference between type and dtype?

Asked

Viewed 2,149 times

3

Based on a previous question, vi 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 there is dtype. What difference between type and dtype? In what situation should I use the dtype?

  • 1

    Dude, dtype it’s a numpy thing.

  • But it’s python isn’t it?! It was at a glance I saw something like dtype('float64'), and I didn’t understand... I thought it was something related.

  • 1

    @Acklay: Are there any questions yet? Want some more examples in the answer?

  • @jsbueno no doubt. Thank you!

1 answer

3


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

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

dtype is the abbreviation of data typeand is used in numpy and related numerical/scientific biblitoecas to identify the type of data that will be contained in an object.

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

For example, a variable x = 1 has a Python number, 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 it to be done y.dtype and the default response is "float64" - which indicates that each number within the "y" array is a 64bit floating point number. Being able to specify dtype in the case of numpy structures allows the developer to have control over the type of data and memory consumption he is working with - could be "float32", for less accuracy and half memory consumption, could be "uint8" if your problem involves black and white images and all data is only one byte.

Already in the core Python language, due to the dynamic nature, it makes no sense to detail 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 a machine native integer, or maintained as a string that allows an undetermined number of decimal places - and who is using the number will not even know.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.