AppDividend
Latest Code Tutorials

Python type() Example | How To Check Type In Python

0

Python type() is an inbuilt method that returns the class type of the argument(object) passed as a parameter. The type() function is mostly used for debugging purposes. With one argument, the Python type() function returns the type of an object. Python doesn’t have the same datatypes as C/C++.

How To Check Type Of Variable In Python

Python isinstance() is an inbuilt method that is often used for testing any type of object because it takes the subclasses into account. One of the best ways to obtain the type of variable is to use the Python type() built-in method.

You can use a __name__ attribute to get the name of an object. In Python, names that start with the underscores are semantically not the part of the public API. So, it’s a best practice for developers to avoid using them.

Syntax

type(object)

The object argument is required, and it can be string, integer, list, tuple, set, dictionary, float, etc.

See the following example.

# app.py

str = 'AppDividend'
print(type(str))

int = 123
print(type(int))

float = 21.19
print(type(float))

negative = -19
print(type(negative))

dictionary = {'blog':'AppDividend'}
print(type(dictionary))

list = [1, 2, 3]
print(type(list))

tuple = (19, 21, 46)
print(type(tuple))

See the following output.

How To Check Type Of Variable In Python

Implementation details of ints and floats

In Python 2, an integer is usually a signed integer equal to the implementation’s word width (limited by the system). It’s generally implemented as the long in C. When the integers get bigger than this, we usually convert them to the Python longs (with unlimited precision, not to be confused with C longs).

For example, in the 32 bit Python 2, we can deduce that int is the signed 32-bit integer.

In Python 3, the old integer goes away, and we use (Python’s) long as int, which has unlimited precision.

Don’t use the __class__, a semantically nonpublic API, to get the type of a variable. Use the built-in type() function instead.

And don’t worry too much about the necessary information about Python. I’ve not had to deal with the issues around this myself regularly.

You probably won’t either, and if you do, then you should know enough not to be looking to this answer for what to do.

I highly recommend that you start using the IPython interactive interpreter when dealing with these kinds of questions.

It lets you type the variable_name? And will return the whole list of information about an object including the type and the docstring for the type.

See the following code.

In [9]: var = 1921

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    1921
Namespace:  Interactive
Docstring:

Finally, Python type() Example Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.