Is there any way to check if object is an instance of a class? Not an
instance of a concrete class, but an instance of any class.
I can check that an object is not a class, not a module, not a
traceback etc., but I am interested in a simple solution.
One approach, like you describe in your question, is a process of exclusion, check if it isn't what you want. We check if it's a class, a module, a traceback, an exception, or a function. If it is, then it's not a class instance. Otherwise, we return True, and that's potentially useful in some cases, plus we build up a library of little helpers along the way.
Here is some code which defines a set of type checkers and then combines them all to exclude various things we don't care about for this problem.
from types import (
BuiltinFunctionType,
BuiltinMethodType,
FunctionType,
MethodType,
LambdaType,
ModuleType,
TracebackType,
)
from functools import partial
from toolz import curry
import inspect
def isfunction(variable: any) -> bool:
return isinstance(
variable,
(
BuiltinFunctionType,
BuiltinMethodType,
FunctionType,
MethodType,
LambdaType,
partial,
curry
),
)
isclass = inspect.isclass
def ismodule(variable: any) -> bool:
return isinstance(variable, ModuleType)
def isexception(variable: any) -> bool:
return isinstance(variable, Exception)
def istraceback(variable: any) -> bool:
return isinstance(variable, TracebackType)
def isclassinstance(x: any) -> bool:
if isfunction(x) or isclass(x) or ismodule(x) or istraceback(x) or isexception(x):
return False
return True
keep in mind, from a hella abstract perspective, everything is a thing, even categories of things or functions ... but from a practical perspective, this could help avoid mistaking MyClass for my_class_instance (the python community also does this informally with PascalCase vs snake_case)
we could improve this