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
