Python check type: How to Check Data type in Python

0
46447
How To Check Type Of Variable In Python | Python type() Tutorial Example

While working with so many data types, a developer often needs to check the data type of a variable to avoid any unnecessary errors and exceptions.

Why checking a data type is important in Python?

If you are debugging a program, you may want to know whether a variable is a string or an integer, and that’s why you need to find its data type.

Every value in Python has a datatype. Everything is an object in Python programming; data types are classes, and variables are these classes’ instances (objects).

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

Type checking vs. Type casting

The main difference between type checking and casting is that you convert a variable to another data type in type casting. We are just getting or printing the variable’s data type in type checking.

There is no conversion of data types in Type checking, but it is in Type casting.

When to use type checking?

When you want to match what is expected in its usage context, Type checking is done by the type checker that verifies the type of a construct.

In strongly typed languages, you get an error if the data types do not match the expression. It does not matter if the type is specified at compile time (static types) or runtime (dynamic types).

Let’s find out how to check the type of a variable in Python and how to implement a type checker.

How to check data type in Python

To check the data type of a variable in Python, use the type() method. The type() is a built-in Python method that returns the class type of the argument(object) passed as a parameter. You place the variable inside a type() function, and Python returns the data type.

The type() function is mainly used for debugging purposes. With one argument, the Python type() function returns the type of an object. Unfortunately, Python doesn’t have the same datatypes as C/C++.

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

Syntax

type(object)

Parameters

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

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, we usually convert them to Python longs (with unlimited precision, not to be confused with C longs).

For example, in 32-bit Python 2, we 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 variable type. 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, you should know enough not to look to this answer for what to do.

I recommend you use the IPython interactive interpreter when dealing with these questions. It lets you type the variable_.ame? And will return the whole list of information about an object, including the type and the docstring of the type.

In [9]: var = 1921

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

Don’t use __class__ to check the data type in Python.

In Python, names that start with underscores are semantically not a part of the public API, and it’s a best practice for users to avoid using them. (Except when it’s compulsory.)

Since type gives us an object class, we should avoid getting __class__ directly.

class Foo(object):
    def foo(self):
        print(self.__class__)

f = Foo()
f.foo()

Output

Let’s use type() function syntax, which is much better than this.

<pre class="lang:python decode:true">class Foo(object):
    def foo(self):
        print(type(self))


f = Foo()
f.foo()
</pre>
&nbsp;

Output

<class '__main__.Foo'>

 Don’t use __class__, a semantically nonpublic API, to get the variable type. Use type instead.

And don’t worry too much about the implementation details in Python. I have not had to deal with issues around this myself. You probably won’t either, and if you really do, you should know enough not to be looking to this answer for what to do.

IPython interpreter

Use IPython interactive interpreter when dealing with questions like type checking in Python. For example, it lets you type variable_name. And it will return a complete list of information about the object, including a type and the docstring for the type.

In [9]: var = 11

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    11
Namespace:  Interactive
Docstring:
    int(x[, base]) -> integer

Convert a string to an integer, if possible. A floating-point argument will be truncated towards zero (this does not include a string representation of a floating-point number!) When converting the string, use an optional base.

It is the error to supply the base when converting a non-string.

If the argument is outside an integer range, a long object will be returned instead.

That’s it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

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