[Fwd: Re: managed lists?]
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Tue May 22 05:04:11 EDT 2007
En Tue, 22 May 2007 04:13:38 -0300, Jorgen Bodde
<jorgen.maillist at gmail.com> escribió:
> Thanks. I agree that it is only 'me' that is the one doing it wrong.
> But consider this scenario:
>
> - Somewhere in my app I add a wrong type to an open regular list
> - The app continues like it should
> - After a (long) while I need to perform some search on the list, or
> whatever
> - Exception occurs
>
> It makes it hard to test this way. For example I can do something to
> that list and not know about it much later .. If it blows up in my
> face, I can fix it, but when that error hinders people who are using
> my application, it is much worse.
You could use something like this to make a "restricted list":
class RestrictedList(list):
def __init__(self, items, itemclass_=None):
self.itemclass_ = itemclass_
for item in items:
self.append(item)
def check(self, item):
if not isinstance(item, self.itemclass_):
raise ValueError("This list can only contain %r instances" %
self.itemclass_)
def __setitem__(self, index, item):
if not isinstance(index,int):
raise NotImplementedError
self.check(item)
list.__setitem__(self, index, item)
def __setslice__(self, *args):
raise NotImplementedError
def append(self, item):
self.check(item)
list.append(self, item)
def insert(self, index, item):
self.check(item)
list.insert(self, index, item)
def extend(self, items):
for item in items:
self.append(item)
I think I'm catching all the ways someone could add a new item to this
list.
You may change the check() method to test for another type of conditions
instead of isinstance; by example, to ensure that all items have a "write"
method (and could be used as file-like objects to output data):
def check(self, item):
try: item.write
except AttributeError:
raise ValueError("blah blah...")
--
Gabriel Genellina
More information about the Python-list
mailing list