liveBook · Manning

Typed list

As explained in The Quick Python Book, Fourth Edition

A typed list is a list abstraction that restricts its elements to an allowed type or set of types.

A typed list restricts its elements to one allowed type. Adding a value of another type raises an error, catching some problems earlier in development. Python does not provide typed lists as a built-in feature, but a class can enforce the restriction. section 17.8

A basic typed-list implementation follows these rules:

  • Pass an example element, such as "Hello", to establish the permitted type; that example is not stored as list data. section 17.8
  • Optionally pass an initial list; its elements are checked during construction, and mismatches raise TypeError. section 17.8
  • Implement __setitem__ and __getitem__ so indexed assignment and access behave like ordinary list operations while assignments remain checked. section 17.8
  • Alternatively, subclass list and override only the type-checking path; inherited operations such as sort and del continue to work. section 17.9.1

A checked string list

x = TypedList("", 5 * [""]) x[2] = "Hello" x[3] = "There" print(x[2] + " " + x[3]) # Hello There The same object can be unpacked like a list, producing ('', '', 'Hello', 'There') for the first four values.

class TypedListList(list):
    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)
        super().__init__(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)
        super().__setitem__(i, element)
 
x = TypedListList("", 5 * [""])
x[2] = "Hello"
x[3] = "There"
print(x[2] + ' ' + x[3])
 
Hello There
 
a, b, c, d, e = x
a, b, c, d
 
('', '', 'Hello', 'There')
 
x[:]
 
['', '', 'Hello', 'There', '']
 
del x[2]
x[:]
 
['', '', 'There', '']
 
x.sort()
x[:]
 
['', '', '', 'There']

Browse the list-subclass implementation, which preserves ordinary list operations while checking assigned values. section 17.9.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains construction, initialization checks, indexed access, assignment checks, and list subclassing, without discussing broader type-system design.
Examples
Demonstrates string lists, initial values, indexed assignments, printed output, unpacking, and slicing.
What it assumes
Assumes general Python knowledge and demonstrates special methods, type, isinstance, and inheritance through the implementation.
What you can do after
Build it from scratch or by subclassing list, then validate initial values and indexed assignments against an example-derived type.
How it connects
Connects typed lists with Python special methods, type checking, list subclassing, inheritance, and built-in list operations.

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.