jeeyoungk jeeyoungk - 1 year ago 48
Python Question

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

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 "
" with ???, but I realized that
is a keyword in python.

Answer Source

Even better: use the inspect.isclass function.

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

>>> x = X()
>>> isinstance(x, X)
>>> y = 25
>>> isinstance(y, X)