The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
00:41 Accepted answer (Score 463)
00:57 Answer 2 (Score 62)
01:08 Answer 3 (Score 49)
01:30 Answer 4 (Score 38)
01:43 Thank you

--

Full question
https://stackoverflow.com/questions/3957...

Accepted answer links:
[inspect.isclass]: https://docs.python.org/library/inspect....

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #reflection

#avk47



ACCEPTED ANSWER

Score 498


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



ANSWER 2

Score 75


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



ANSWER 3

Score 55


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

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

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



ANSWER 4

Score 45


isinstance(X, type)

Return True if X is class and False if not.