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
from my_module import MyClasswill be class object, not instance of class, similiarly for traceback, function, module.inspectmodule contains special checking functions for this type of objects, but no function for instances of classes. Roughly, i want to detect all objects, for whichprint objwill print<instance of ...>(if no special printing defined for class) - exbluesbreakertypebut anyone can define a metaclass, IIRC even without inheriting fromtype). A traceback is just an instance oftraceback. A function is just an instance offunction. A method is just an instance of a class too (which depends on what exactly you mean by method). You'll have to be more specific -- or even better, just tell us your actual problem. - user395760