TypedList in Python

Introduction

Python, by default, does not enforce type constraints on lists, allowing them to contain elements of varying types. However, there are scenarios where maintaining a homogeneous list is desirable. The TypedList class is a custom implementation that enforces type consistency within a list, ensuring all elements are of the same type.

Implementation of TypedList

The TypedList class is designed to mimic the behavior of a standard Python list while enforcing type constraints. It uses Python's built-in type and isinstance functions to check the type of objects. Below is the implementation of the TypedList class:

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]

Key Features

  • Type Enforcement: The TypedList class requires an example element during initialization to determine the type of elements it will accept. This example element is not stored but is used to set the type constraint.

  • Initialization: The constructor accepts an optional initial list. If provided, it checks that all elements in this list match the type of the example element.

  • Element Access and Assignment: The class implements __getitem__ and __setitem__ methods to allow element access and assignment using the bracket notation ([]). These methods ensure that any element added to the list matches the specified type.

Usage Example

The TypedList class can be used as follows:

x = TypedList("", 5 * [""])
x[2] = "Hello"
x[3] = "There"
print(x[2] + ' ' + x[3])

a, b, c, d, e = x

Output:

Hello There
('', '', 'Hello', 'There')

In this example, x is a TypedList that can only contain strings. The assignments to x[2] and x[3] are valid because they are strings. The print statement and unpacking operation demonstrate how TypedList can be used similarly to a regular list, with the added benefit of type safety.

Conclusion

The TypedList class provides a way to enforce type homogeneity in lists, which can be useful in scenarios where type consistency is critical. By implementing special methods like __getitem__ and __setitem__, the class integrates seamlessly with Python's syntax for list operations, offering both flexibility and safety.