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

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


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


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


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))