Check Object Type Python

Are you looking for the perfect python beginners’ tutorial to learn complete knowledge about python programming? Then, our PythonArray is the one-stop destination for beginners and developers. In this tutorial, we are going to explain to you the fundamentals of how to check for object type in python.

We have already known that there are various types of objects in python programming like lists, strings, integers, etc. If you find it difficult to figure out the type of object that you’re performing the code, then Python has the best solution ie, a built-in functioning for determining the object type. Check out the following modules of this Check Object Types Python Tutorial and gain proper knowledge about it.

The Tutorial of Determine the Type of an Object in Python contains the following stuff:

How to Check for Object Type in Python?

If your naked eye cheated you to find the difference between one type or another then python will help you determine the object type that you need by using the built-in functions ie., type() function and isinstance() function. With the help of these two functions, you can easily figure out the type of object in python programming. Just follow the below modules carefully and understand how to determine object type in python with ease.

Read More: 

What is Type() Function in Python?

Python Type() function is simple to utilize and assists you to find out quickly about what type of Python objects you’re working with. Also, it is likely to provide three arguments to type(), i.e., type(name, bases, dict), in such case, it will return you a new type object. Types are written like this: <class ‘int’>

Syntax for Type():

The function of type() can be written in two ways. They are as follows:

type(object)
type(namr, bases, dict)

Parameters of type(object)

  • object: This is a mandatory parameter.

Parameters of type(name, bases, dict)

  • name: Name of the class.
  • bases: (optional). This is an optional parameter, and it is the base class
  • dict: (optional). This is an optional parameter, and it is a namespace that has the definition of the class.

Return Value

  • If the object is the only parameter passed to type() then it will return you the type of the object.
  • If the params passed to type is a type(object, bases, dict), then it will return a new type of object.

How Type() function works to check Object Type in Python?

Using the type() function in Python is an honest and almost easy way to check what type of objects you’re operating with, so play around with it until you would feel comfortable using it in any coding situation.

To use it, you just need to pass the object through the function as a parameter and you’ll quickly get your answer. For example, if you’re looking to find the type of object that looks like this:

one = ['purple', 'yellow', 'green']

You’ll just need to use the type() function, like this:

type(one)

You may already know the answer because of how the object is formatted (any objects between two [] brackets is a list), but your output will be this:

<type 'list'>

You can also use the type() slightly differently, using the following syntax:

type(one) is a list
>>>True

In the example above, the first line is how you’d use the type() function and the second line is the output that tells you if the object is the type you think or not (in this case, it is in fact a list).

Example of type()

In the following instance, we have used a string value, number, float value, a complex number, list, tuple, dict, and set. Now, we will use the variables with type to see the output for each of them.

str_list = "Welcome to Guru99"
age = 50
pi = 3.14
c_num = 3j+10
my_list = ["A", "B", "C", "D"]
my_tuple = ("A", "B", "C", "D")
my_dict = {"A":"a", "B":"b", "C":"c", "D":"d"}
my_set = {'A', 'B', 'C', 'D'}

print("The type is : ",type(str_list))
print("The type is : ",type(age))
print("The type is : ",type(pi))
print("The type is : ",type(c_num))
print("The type is : ",type(my_list))
print("The type is : ",type(my_tuple))
print("The type is : ",type(my_dict))
print("The type is : ",type(my_set))

Result:

The type is :<class 'str'>
The type is :<class 'int'>
The type is :<class 'float'>
The type is :<class 'complex'>
The type is :<class 'list'>
The type is :<class 'tuple'>
The type is :<class 'dict'>
The type is :<class 'set'>

Example of Class type(object)

#!/usr/bin/env python3

# Assigned a list to var object
var = ['10','abcd','1234']

# Print the type of variable
print(type(var))

Output:

<class 'list'>

Example Using the name, bases, and dict in type()

In this instance, we create a class and print individual properties:

#!/usr/bin/env python3

NewClass1 = type('NewClass1', (object,), {'__doc__': 'NewClass1 Documentation', 'var': 'string'})

print (NewClass1.__class__)
print(NewClass1.__bases__)
print(NewClass1.__dict__)

Output:

<class 'type'>
(<class 'object'>,)
{'__doc__': 'NewClass1 Documentation', 'var': 'string', '__module__': '__main__', '__dict__': <attribute '__dict__' of 'NewClass1' objects>, '__weakref__': <attribute '__weakref__' of 'NewClass1' objects>}
NewClass1 Documentation

What is isinstance() Function in Python?

The Python isinstance() function determines if the object (first argument) is an instance or subclass of classinfoclass argument, or of a (direct, indirect, or virtual) subclass thereof. You can use a tuple as the second argument. Returns True if it is an instance of any type.

Syntax for isinstance()

isinstance(object, classinfo)

Parameters of python isinstance()

The isinstance() function in python takes two parameters:

  • object: object to be checked
  • classinfo: class, type, or tuple of classes and types

Return Value

Trueif the object is an instance or subclass of a class, or any element of the tuple false otherwise. If class info is not a type or tuple of types, a TypeError exception is raised.

Example of isinstance() Function

# Python code for  isinstance()
class Test:
    a = 5
    
TestInstance = Test()
  
print(isinstance(TestInstance, Test))
print(isinstance(TestInstance, (list, tuple)))
print(isinstance(TestInstance, (list, tuple, Test)))

Output: 

True
False
True

Difference between type() and isinstance() in Python | type() vs isinstance()

type() isinstance()
Python has a built-in function called type() that helps you find the class type of the variable given as input. Python has a built-in function called isinstance() that compares the value with the type given. If the value and type given matches it will return true otherwise false.
The return value is a type of object. The return value is a Boolean i.e true or false.
class A:
my_listA = [1,2,3]

class B(A):
my_listB = [1,2,3]

print(type(A()) == A)
print(type(B()) == A)

Output:

True
False

If type the subclass check gives back a false.

class A:
my_listA = [1,2,3]

class B(A):
my_listB = [1,2,3]

print(isinstance(A(), A))
print(isinstance(B(), A))

Output:

True
True

isinstance() gives a truthy value when checked with a subclass.

Leave a Reply

Your email address will not be published.