How to check whether a variable is a class or not?
The answer to "how to identify if a variable is a class" lies in using inspect.isclass(variable)
, provided by Python's inspect
module.
It will return True
if the variable is a class, False
otherwise.
Step-by-step guide through Python's type checking
Let's guide through the Python trail to understand the wild west of checking whether variables are classes or not.
The Type Sheriff: type()
The simple notion behind the type()
function is that for any class fed into it, it should return <class 'type'>
. This includes user-defined classes!
Identity Theft Check: isinstance()
Classes impersonating other types? No more with isinstance()
. Classes are essentially instances of the type
type (unsurprisingly).
Python 2's Old West: types.ClassType
In the case of Python 2, a rogue called types.ClassType
represents old-style classes. Capture both new and old-style classes with (type, types.ClassType)
.
Spotting a class in a crowd
Learn to decipher whether a variable is a class based on various recognizable traits and missteps.
Indicators to tick off
Certain attributes unique to classes like __doc__
and __module__
usually don't parade around in other variables:
Avoid the Python Police: 'class' keyword
Keywords like class
are reserved. Stay on the right side of the law! Use type
for class variable checks, but remember to keep your variables clearly named.
Crossing the Python 2 and 3 divide: six.class_types
The six
library is a peace treaty between Python 2 and 3, with its six.class_types
offering:
Mastering the art of class detection
Let's deep dive into Python's mystical world of 'reflection' and 'custom inference' while class-detecting.
Metaclass Mystery • Reflection
Python's magic trick of reflection lets you peek and prod at your classes. Metaphorically check the DNA of your class!
Custom Type Checks
Craft your custom detection function to branch out from usual indicators - beyond the classes, into the unknown.
Remember to deep dive only when you're confident swimming in Python's class pool.
Was this article helpful?