How to Check Whether a Variable is a Class or Not?

This tutorial explores the ways one can check if a variable is a class.

The direct way to check if a variable is a class, is to use the isclass() runtime service, from Python’s inspect module.  Use isclass() in conjunction with Python’s isinstance() built-in function, to examine a variable. Both of these return a Boolean as the answer for the test.

You can watch me explain the video while you scroll over this article:

Note: All the solutions provided below have been verified using Python 3.9.0b5

Problem Formulation

Imagine the following class in Python.

class MyFinxterClass1(object):
    pass

Given the following instantiations, how does one tell whether the variable is a class?

variable1 = MyFinxterClass1
variable2 = MyFinxterClass1()

Background

As always, the above problem has quite a simple solution in Python.  In every coder’s life, sooner or later they have to determine the nature of any object or variable. A common use is to decide which path to take in code. Python provides various ways to narrow down the nature of any object or variable. This specific blog explores the way to check whether a variable is a class. Along the way, this blog also explores various tools to examine a variable. After all, the Finxter Academy is all about teaching and providing helpful tools to thoughtfully and successfully code in Python.  

Enough Dawdling!! Show me!!

Ok! Ok!! Did you know that Movement, any Movement, is the essence of life.  Ponder it in the back of your mind as you read this blog. Remember to get up and move, stretch, walk, take a deep breath, every 10-15 minutes as you take a deep dive into Python Coding.

The Python Standard Library contains the ‘inspect’ module that provides useful runtime services. These services provide useful information about live objects such as modules, classes, etc.. The inspect.isclass() in particular, helps to determine if a variable is a class. Let’s see how this is done…

$ python
Python 3.9.0b5 (default, Oct 19 2020, 11:11:59) 
>>> 
>>> ## Declare the class. Note that the 'pass' keyword is used to keep
>>> ## the code simple and easy to understand. It translates to a NOP.
>>> class MyFinxterClass1(object):
...     pass
... 
>>> ## 'inspect' is a Python Standard Library Module that contains a lot of
>>> ## useful Python Runtime Services
>>> import inspect
>>> 
>>> ## First test the Class itself...
>>> inspect.isclass(MyFinxterClass1)
True
>>> ## This is good!! We now know for sure, MyFinxterClass1 is a Class
>>> 
>>> ## Now, instantiate the Class…
>>> ## variable2 is an instance of Class MyFinxterClass1.
>>> variable2 = MyFinxterClass1()
>>> ## But what is variable1? The test for variable1 has a hint.
>>> variable1 = MyFinxterClass1
>>> 
>>> ## Next, test the variables...
>>> inspect.isclass(variable2)
False
>>> ## Still good!! Variable2 is an instance, hence not a class.  
>>>
>>> ## But what about variable1?
>>> inspect.isclass(variable1)
True
>>> ## variable1 is an alias of MyFinxterClass1, hence it is also considered a class.

Note: The keyword ‘pass’ was used to keep the code simple and easy to understand. In Python, it represents a NOP (No OPeration), i.e., it is valid code but not a comment. In the example above, the keyword ‘pass’ helps to form the body of the Class while keeping it simple and bare-bones.

As one can see from above, inspect.isclass() is the best and easiest way to check whether a variable is a class or not.  Besides, the inspect module is part of the Python Standard Library. One can rest assured that it passed muster by the tough as nails Python Community. The test worked for the class itself as well as its instance and its alias. But, does it work for Python’s in-built classes? Let’s see…

$ python
Python 3.9.0b5 (default, Oct 19 2020, 11:11:59) 
>>> 
>>> ## First lets test the list class.
>>> ## Declare a list variable...
>>> l1 = [1, 2, 3, 4]
>>> ## Make sure it is a list… Yup! It is a list!!
>>> type(l1)
<class 'list'>
>>>
>>> ## Is ‘list’ a class? It should be!!!. Yup! It is a class!!
>>> inspect.isclass(list)
True
>>> ## What about the variable? 
>>> inspect.isclass(l1)
False
>>> ## So far, so good.  What about a Set?
>>> s1 = {1, 2, 3, 4}
>>> type(s1)
<class 'set'>
>>>
>>> inspect.isclass(set)
True
>>> inspect.isclass(s1)
False
>>> 
>>> ## Hmm, we are beginning to see a pattern here! Excellent!!
>>> t1 = (1, 2, 3, 4)
>>> type(t1)
<class 'tuple'>
>>> inspect.isclass(tuple)
True
>>> inspect.isclass(t1)
False
>>> 

So yes! It seems like inspect.isclass() works well to check whether a variable is a class.

You Mentioned isinstance()! What Is That?

Python is an object-oriented language.  As such, one can create abstract classes, derived classes, virtual classes, etc.. It then becomes important to figure out if a given variable is an instance of a specific Class.  This is when isintance() becomes useful. The method isinstance(object, classinfo) is a Python built-in function. It tests if the ‘object’ argument is an instance of the ‘classinfo‘ argument. Let’s see how this works.

Try to use isinstance() on Python’s built-in Classes such as lists, sets and tuples.

$ python
Python 3.9.0b5 (default, Oct 19 2020, 11:11:59) 
>>> 
>>> ## Declare a list, a set and a tuple variable...
>>> l1 = [1, 2, 3, 4]
>>> s1 = {1, 2, 3, 4}
>>> t1 = (1, 2, 3, 4)
>>>
>>> ## Now let’s play with the isinstance() built-in Python function.
>>> ## s1 is a ‘set’, not a ‘tuple’
>>> isinstance(s1, tuple)
False
>>> ## But t1 is indeed a ‘tuple’
>>> isinstance(t1, tuple)
True
>>> ## Is s1 really a set? Yes, it is...
>>> isinstance(s1, set)
True
>>> ## What if we ask if t1 is a ‘set’?
>>> isinstance(t1, set)
False
>>> ## Still works!! Doesn't it?? Now we are beginning to have fun, lol!!!
>>> ## What about l1? Yeah! What about it???  Go ahead and test it...
>>> isinstance(l1, list)
True
>>> isinstance(l1, set)
False
>>> isinstance(l1, tuple)
False 

The reader should go ahead and try this out on all the built-in Classes (also known as Data Types) in Python. The reader has a chance to become famous if they find a bug in the Python language!! Yes, Python is nothing, if not for its great community of users.

So what about the MyFinxterClass and its variants and instances, one may ask.  Would isinstance() work on that? Let’s find out…

>>> ## Declare the class. Note that the 'pass' keyword is used to keep
>>> ## the code simple and easy to understand. It translates to a NOP.
>>> class MyFinxterClass1(object):
...     pass
... 
>>> ## 'inspect' is a Python Standard Library that contains a lot of
>>> ## useful Python Runtime Services
>>> import inspect
>>> 
>>> ## Declare a Class derived from MyFinxterClass1
>>> class Second1(MyFinxterClass1):
...     pass
... 
>>> ## Declare another Class derived from MyFinxterClass1
>>> ## Note that Second1 and Second2 are derived sibling classes because
>>> ## both of them are derived from MyFinxterClass1
>>> class Second2(MyFinxterClass1):
...     pass
... 
>>> ## Instantiate the derived Classes
>>> variable3 = Second1()
>>> variable4 = Second2()
>>> 
>>> ## Test whether they are classes. They should be!!!
>>> inspect.isclass(MyFinxterClass1)
True
>>> inspect.isclass(Second1)
True
>>> inspect.isclass(Second2)
True
>>> 
>>> ## So far so good. What about the instances? Do they have the 
>>> ## the relationships we think they should have?  Lets See...
>>> isinstance(variable3, Second1)
True
>>> ## Yes, variable3 is an instance of Second1.
>>> isinstance(variable3, MyFinxterClass1)
True
>>> ## Yes, variable3 is *also* an instance of MyFinxterClass1. This is 
>>> ## because Second1 is derived from MyFinxterClass1. Makes Sense!!
>>> 
>>> ## This is the interesting one!! Second1 and Second2 are siblings.
>>> ## So yes, they are related because MyFinxterClass1 is their parent.
>>> ## But variable3 is *not* an instance of Second2. Therefore....
>>> isinstance(variable3, Second2)
False
>>> ## Phew!! What a relief :)
>>> 
>>> ## In a similar vein, can the reader predict answers to the following?
>>> isinstance(variable4, Second1)
False
>>> isinstance(variable4, MyFinxterClass1)
True
>>> isinstance(variable4, Second2)
True
>>> 

How Is type() Related To All Of This?

As the reader may have noticed, Python as a language is very intuitive and easy to learn.  The function type() is a Python built-in function. With one argument, type(object) returns…, you guessed it, the ‘type‘ of the object argument. There are other fun variations of the type() function, but that is for another tutorial.

So what does type() tell us about the classes, variables, and instances we created above? Let’s see…

$ python
Python 3.9.0b5 (default, Oct 19 2020, 11:11:59) 
>>>
>>> ## Declare the Classes and Instantiate them as was done before
>>> ## in code snippets shown above.
>>> class MyFinxterClass1(object):
...     pass
... 
>>> variable1 = MyFinxterClass1
>>> variable2 = MyFinxterClass1()
>>> 
>>> class Second1(MyFinxterClass1):
...     pass
... 
>>> class Second2(MyFinxterClass1):
...     pass
...     
>>> variable3 = Second1()
>>> variable4 = Second2()
>>> 
>>> ## Next, run the type() function on each of them.
>>> type(MyFinxterClass1)
<class 'type'>
>>> type(Second1)
<class 'type'>
>>> type(Second2)
<class 'type'>
>>> type(variable1)
<class 'type'>
>>> ## So, User defined classes and their aliases, show up as the ‘type’ metaclass
>>>
>>> ## On the other hand, for the instantiations(i.e. variables) type() shows the
>>> ## appropriate class. 
>>> type(variable2)
<class '__main__.MyFinxterClass1'>
>>> type(variable3)
<class '__main__.Second1'>
>>> type(variable4)
<class '__main__.Second2'>
>>> 
>>> ## What about the Python built-in classes. Well, declare a list, a set and a tuple
>>> ## variable...
>>> l1 = [1, 2, 3, 4]
>>> s1 = {1, 2, 3, 4}
>>> t1 = (1, 2, 3, 4)
>>> 
>>> ## As above, run the type() function on each of them. Again, type() shows the
>>> ## appropriate class. 
>>> type(l1)
<class 'list'>
>>> type(s1)
<class 'set'>
>>> type(t1)
<class 'tuple'>
>>> 
>>> ## What happens when type() is run on Python's built-in classes
>>> ## such as list, set and tuple? 
>>> type(list)
<class 'type'>
>>> type(set)
<class 'type'>
>>> type(tuple)
<class 'type'>
>>> 
>>> ## Again, just as the user defined classes, the Python built-in classes show up
>>> ## as the ‘type’ metaclass.
>>>

Conclusion

One can use inspect.isclass() to check if a variable is a class. Use isinstance() to check the ‘is a’ relation of the object with its parent class.  Finally, use type() to find the ‘type‘ of the item.

Folks that work with computers often tend to spend long hours motionless.  We (yes me-too) often forget to even blink our eyes because coding is so very intense. Always remember to take breaks often. Move around, take deep breaths, and blink. I can assure you, it makes coding fun.

Finxter Academy

This blog was brought to you by Girish Rao, a student of Finxter Academy. You can find his Upwork profile here.

Reference

All research for this blog article was done using Python Documents, the Google Search Engine and the shared knowledge-base of the Finxter Academy and the Stack Overflow Communities.