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
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
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
isinstance(X, type)
Return True
if X
is class and False
if not.