inspection
isinstance()
Returns True if the object is an instance of classinfo (a class or tuple of classes). Respects the class hierarchy — subclasses count.
isinstance(object, classinfo) Parameters
| Parameter | Purpose |
|---|---|
| object | Value being tested |
| classinfo | Class, tuple of classes, or PEP 604 union (int | str) |
Examples
isinstance(1, int) Returns True
isinstance(True, int) Returns True (bool is int subclass)
isinstance('x', (int, str)) Returns True
isinstance(1, int | str) Returns True (Python 3.10+ union)
Gotcha
isinstance(True, int) is True because bool subclasses int — check for bool explicitly if it matters.
Related built-ins
type()
Returns the type of an object, or dynamically creates a new type when called with three arguments. type(x) is the runtime class of x.
hasattr()
Returns True if the object has an attribute with the given name. Implemented by calling getattr() and catching AttributeError.
getattr()
Returns the value of the named attribute of object. If the attribute is missing, returns default (if given) or raises AttributeError.
len()
Returns the number of items in a container. Calls the object's __len__ method.