Categories
Python Answers

How to determine the type of an object with Python?

Spread the love

Sometimes, we want to determine the type of an object with Python.

In this article, we’ll look at how to determine the type of an object with Python.

How to determine the type of an object with Python?

To determine the type of an object with Python, we can use the type or isinstance functions.

For instance, we write

type([]) is list

class Test (object):
    pass
a = Test()
type(a) is Test 

to check if [] is a list with

type([]) is list

And we check if a is a Test class instance with

type(a) is Test 

type returns the class of the variable.

We can use isinstance to check if a variable is of a given type.

For instance, we write

isinstance(b, Test)

to check if b is a instance of the Test class. It returns True if b is a Test instance and False otherwise.

Conclusion

To determine the type of an object with Python, we can use the type or isinstance functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *