How to check whether a variable is a class or not?

PythonReflection

Python Problem Overview


I was wondering how to check whether a variable is a class (not an instance!) or not.

I've tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don't know what type would a class will have.

For example, in the following code

class Foo: pass  
isinstance(Foo, **???**) # i want to make this return True.

I tried to substitute "class" with ???, but I realized that class is a keyword in python.

Python Solutions


Solution 1 - Python

Even better: use the inspect.isclass function.

>>> import inspect
>>> class X(object):
...     pass
... 
>>> inspect.isclass(X)
True

>>> x = X()
>>> isinstance(x, X)
True
>>> inspect.isclass(x)
False

Solution 2 - Python

>>> class X(object):
...     pass
... 
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True

Solution 3 - Python

The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented

def isclass(object):
    """Return true if the object is a class.

    Class objects provide these attributes:
        __doc__         documentation string
        __module__      name of module in which this class was defined"""
    return isinstance(object, (type, types.ClassType))

Solution 4 - Python

isinstance(X, type)

Return True if X is class and False if not.

Solution 5 - Python

This check is compatible with both Python 2.x and Python 3.x.

import six
isinstance(obj, six.class_types)

This is basically a wrapper function that performs the same check as in andrea_crotti answer.

Example:

>>> import datetime
>>> isinstance(datetime.date, six.class_types)
>>> True
>>> isinstance(datetime.date.min, six.class_types)
>>> False

Solution 6 - Python

Benjamin Peterson is correct about the use of inspect.isclass() for this job. But note that you can test if a Class object is a specific Class, and therefore implicitly a Class, using the built-in function issubclass. Depending on your use-case this can be more pythonic.

from typing import Type, Any
def isclass(cl: Type[Any]):
    try:
        return issubclass(cl, cl)
    except TypeError:
        return False

Can then be used like this:

>>> class X():
...     pass
... 
>>> isclass(X)
True
>>> isclass(X())
False

Solution 7 - Python

class Foo: is called old style class and class X(object): is called new style class.

Check this https://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python . New style is recommended. Read about "unifying types and classes"

Solution 8 - Python

simplest way is to use inspect.isclass as posted in the most-voted answer.
the implementation details could be found at python2 inspect and python3 inspect.
for new-style class: isinstance(object, type)
for old-style class: isinstance(object, types.ClassType)
em, for old-style class, it is using types.ClassType, here is the code from types.py:

class _C:
    def _m(self): pass
ClassType = type(_C)

Solution 9 - Python

There is an alternative way to check it:

import inspect

class cls():
     print(None)

inspect.isclass(cls)

Reference: https://www.kite.com/python/docs/inspect.isclass

Solution 10 - Python

Well, inspect.isclass is not working for me, instead, try this

class foo:
    pass

var = foo()

if str(type(var)).split(".")[0] == "<class '__main__":
    print("this is a class")
else:
    print(str(type(var)).split(".")[0])

So basically, type(var) is <class 'a type'>

Example: <class 'int' But, when var is a class, it will appear something like <class '__main__.classname'>

So we split the string into <class '__main__ and we compare using if, if the string fit perfectly then it's a class

enter image description here

Solution 11 - Python

In some cases (depending on your system), a simple test is to see if your variable has a __module__ attribute.

if getattr(my_variable,'__module__', None):
    print(my_variable, ".__module__ is ",my_variable.__module__)
else:
    print(my_variable,' has no __module__.')

int, float, dict, list, str etc do not have __module__

Solution 12 - Python

There are some working solutions here already, but here's another one:

>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjeeyoungkView Question on Stackoverflow
Solution 1 - PythonBenjamin PetersonView Answer on Stackoverflow
Solution 2 - PythonS.LottView Answer on Stackoverflow
Solution 3 - Pythonandrea_crottiView Answer on Stackoverflow
Solution 4 - PythonqnubView Answer on Stackoverflow
Solution 5 - PythonSergeyView Answer on Stackoverflow
Solution 6 - PythonomniView Answer on Stackoverflow
Solution 7 - PythonJV.View Answer on Stackoverflow
Solution 8 - Pythonlyu.lView Answer on Stackoverflow
Solution 9 - PythonMd. Nazmus Sanib ChowdhuryView Answer on Stackoverflow
Solution 10 - PythonKirro SmithView Answer on Stackoverflow
Solution 11 - PythonBen LawView Answer on Stackoverflow
Solution 12 - PythonZtyxView Answer on Stackoverflow