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

后端 未结 9 668
暖寄归人
暖寄归人 2020-11-28 19:14

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

9条回答
  •  爱一瞬间的悲伤
    2020-11-28 19:34

    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
    

提交回复
热议问题