Entry
Typed list
Jul 5th, 2000 10:03
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 303, Python Snippet Support Team
"""
Packages: basic_datatypes.lists
"""
# typedlist.py
"""Provides a class for lists of a certain type, like parametrized classes
in Eiffel, or template classes in C. While this concept is an extension of
those languages mentioned, it rather seems to be a *restriction* of Python's
capabilities."""
from UserList import UserList
# Based on UserList, so I can reuse most of that class; its subclass must
# only make sure that added values are of the correct type.
class TypedList(UserList):
def __init__(self, aType):
UserList.__init__(self)
self.__type = aType
def append(self, x):
if type(x) != self.__type:
raise TypeError, 'TypedList: can only add objects of %s' % self.__type
self.data.append(x)
if __name__ == "__main__":
tl = TypedList(type(3)) # a list of integers, obviously
# trying to append something else
try:
tl.append('Hoi')
except TypeError, msg:
print msg
tl.append(35) # OK