Type checking tests whether values have expected types. In Python, type objects can be compared for equality, allowing functions and methods to check their inputs. section 17.2 section 17.12
type("Hello") == type("Goodbye")
True
type("Hello") == type(5)
False
Comparing type objects shows that two strings have the same type, while a string and an integer do not. section 17.2
A typed list can record the type of an example element, check initial elements, and reject assignments of a different type with TypeError. The list below uses isinstance to check that the initial container is a list, but compares element types for equality. section 17.8
class TypedList:
def __init__(self, example_element, initial_list=[]):
self.type = type(example_element)
if not isinstance(initial_list, list):
raise TypeError("Second argument of TypedList must "
"be a list.")
for element in initial_list:
self.__check(element)
self.elements = initial_list[:]
def __check(self, element):
if type(element) != self.type:
raise TypeError("Attempted to add an element of "
"incorrect type to a typed list.")
def __setitem__(self, i, element):
self.__check(element)
self.elements[i] = element
def __getitem__(self, i):
return self.elements[i]
The private __check method is used both during initialization and before an indexed assignment; __getitem__ delegates access to the stored list. section 17.8
Subclassing list supplies default list operations and lets a class override __setitem__ to check an element before delegating the assignment. Any other methods that add items must also be considered when enforcing a type restriction. section 17.9.1
A string-only dictionary
For a dictionary that stores URL and page strings, override dict.__setitem__ to check keys and values. Construction from tuples or another dictionary can bypass that method, so __init__ must also enforce the restriction; one approach is to initialize the parent first and then check the resulting dictionary. section 17.11
Explicit checks are not always necessary. Duck typing relies on an object’s behavior rather than its type: an iterator, for example, needs to yield values as expected. This can make code more flexible, though bugs may escape detection in larger codebases. Type hints verified by a type checker offer another approach. section 17.4






