Entry
Restricted list
Jul 5th, 2000 10:00
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 134, Python Snippet Support Team
"""
Packages: basic_datatypes.lists;oop
"""
# restrictedlist.py
# A list which filters out certain elements.
from UserList import UserList
class RestrictedList(UserList):
def append(self, x):
if self.filter(x): UserList.append(self, x)
def filter(self, obj):
return 1
def __add__(self, other):
new_rl = self.__class__() # !!!
new_rl.data = self.data[:]
try:
# let's see if this is a sequence
for item in other:
new_rl.append(item)
except:
# it's not a sequence -- try to add this element
new_rl.append(other)
return new_rl
if __name__ == "__main__":
class PositiveIntList(RestrictedList):
def filter(self, x):
if not type(x) in (type(1), type(1L)): return 0
return x >= 0
pil = PositiveIntList()
pil = pil + [1, -2, 3.02, 'x', 5, 8, 9L, 2j]
print pil