Python Glossary Русский

all Python 3Data typesfunction

isinstance()

introspection

Built-in function that checks whether an object belongs to a type or to a tuple of types. Unlike type(), it honors inheritance.

Syntax

isinstance(object, classinfo) -> bool

The main trap is that bool counts as int: isinstance(True, int) returns True because bool subclasses int. When you need one exact type ignoring subclasses, compare type(x) is int; but idiomatic Python usually avoids explicit type checks in favour of duck typing.

Examples

print(isinstance(42, int))  # → True
print(isinstance(3.14, float))  # → True
print(isinstance(True, int))  # → True (bool — подкласс int)
print(isinstance("hi", (int, str)))  # → True (кортеж типов)
print(isinstance([], list))  # → True
def add(a, b):
    if not isinstance(a, (int, float)):
        raise TypeError("Нужно число")
    return a + b
print(add(2, 3))  # → 5

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy