liveBook · Manning

Isinstance

As explained in The Quick Python Book, Fourth Edition

isinstance is a Python built-in function that tests whether an object is an instance of a specified class or tuple of classes.

isinstance(object, class) returns whether an object is an instance of the given class. The second argument can also be a tuple of classes. An instance of a subclass passes a check against its base class. section 17.3

Checking an instance and its base class

class D: pass class E(D): pass e = E() d = D() isinstance(e, E) # True isinstance(e, D) # True isinstance(d, E) # False section 17.3

Use issubclass to check a class against another class. To derive the class to check from an example object, use type: isinstance(value, type(example)). Unlike isinstance, an exact comparison such as type(value) == SomeClass does not accept a subclass instance. section 17.3 section 17.8

A type check can guard an operation before it happens. For example, a dictionary subclass can reject non-string keys or values in __setitem__ by raising TypeError. Initialization needs its own validation: it can first call the parent initializer, then check the resulting keys and values. section 17.11.2

""" Create a dictionary that allows only strings for keys and values"""
 
class StringDict(dict):
    def __setitem__(self, key, value):
        if not isinstance(key, str):
            raise TypeError('key is not a string')     #1
        if not isinstance(value, str):
            raise TypeError('value is not a string')
        super().__setitem__(key, value)
 
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        key_error = any(not isinstance(_, str) 
                         for _ in self.keys())         #2
        if key_error:
            raise TypeError('key is not a string')
        value_error = any(not isinstance(_, str) 
                         for _ in self.values())       #2
        if value_error:
            raise TypeError('value is not a string')

See the string-only dictionary validate assignment and initialization, using any with generator expressions to find invalid entries. section 17.11.2

A typed-list example obtains its allowed element class from an example value with type(example_element), then uses isinstance to validate initial elements. A later version instead compares exact types in a shared check, changing how subclass instances are treated. section 17.8

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains inheritance-aware checks and applies them to assignment and initialization validation, without detailing function internals.
Examples
Uses an inheritance hierarchy, a string-only dictionary, and a typed-list implementation.
What you can do after
Apply it via Python's isinstance to check objects and raise errors for invalid container entries.
How it connects
Connects instance checks to inheritance, type, issubclass, special methods, and generator expressions.

Also explained in

Compare how 2 books explain isinstance →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.