473,378 Members | 1,104 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

ListMixin (WAS: How do you control _all_ items added to a list?)

Nick Coghlan wrote:
Hmm, it might be nice if there was a UserList.ListMixin that was the
counterpart to UserDict.DictMixin


I've thought this occasionally too. One of the tricky issues though is
that often you'd like to define __getitem__ for single items and have
ListMixin add the code for slices. I haven't figured out how to do this
cleanly yet...

STeVe
Jul 18 '05 #1
2 1288
Steven Bethard wrote:
Nick Coghlan wrote:
> Hmm, it might be nice if there was a UserList.ListMixin that was the
> counterpart to UserDict.DictMixin


I've thought this occasionally too. One of the tricky issues though is
that often you'd like to define __getitem__ for single items and have
ListMixin add the code for slices. I haven't figured out how to do this
cleanly yet...

STeVe

I agree that would be useful. One solution would be to ask users to implement
__getsingleitem__ (and not __getitem__) if they want the mixin to handle slice
logic. The following illustrates that, and also falls back to slicing the
iterator if it is provided:

class ProtoListMixin(object):
"""Prototype ListMixin, exploring slice interface and semantics"""
def __getitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.start or 0, index.stop, index.step or 1
if start < 0 or stop < 0 or not stop:
try:
start, stop, step = index.indices(len(self))
except TypeError:
raise TypeError, "unsized object"

try:
getter = self.__getsingleitem__
return [getter(i) for i in range(start, stop, step)]
except AttributeError:
pass
else:
if index < 0:
try:
index = len(self) + index
except TypeError:
raise TypeError, "unsized object"
try:
return self.__getsingleitem__(index)
except AttributeError:
pass
start, stop, step = index, index + 1, None

# Alternatively, try to use the iterator, if available
import itertools
try:
args = [iter(self)]
except AttributeError:
raise TypeError, "Must implement __getsingleitem__ or __iter__"

if start:
args.append(start)
args.append(stop)
if step:
if step < 1:
raise ValueError, "slicing an iterable requires step >=1"
args.append(step)

iterator = itertools.islice(*args)
if isinstance(index, slice):
return list(iterator)
else:
try:
return iterator.next()
except StopIteration:
raise IndexError, "index out of range"
# Users should implement __getsingleitem__ for positive indices

class Index(ProtoListMixin):
def __init__(self, data):
"""For testing, provide a list"""
self._data = data
def __getsingleitem__(self, index):
return self._data[index]

# If __len__ is implemented, negative indices are supported

class IndexLen(Index):
def __len__(self):
return len(self._data)

# If __getsingleitem__ is not implemented, positive slices are returned
# from an iterator

class Iter(ProtoListMixin):
def __init__(self, data):
"""For testing, provide an iterable"""
self._data = data
def __iter__(self):
return iter(self._data)

a = Index(range(10))
a[4] 4 a[4:8] [4, 5, 6, 7] a[-4] Traceback (most recent call last):
File "<input>", line 1, in ?
File "ListMixin", line 22, in __getitem__
TypeError: unsized object
b = IndexLen(range(10))
b[-4] 6
c = Iter(xrange(10))
c[3] 3 c[3:6] [3, 4, 5] c[-3] Traceback (most recent call last):
File "<input>", line 1, in ?
File "ListMixin", line 22, in __getitem__
TypeError: unsized object


Jul 18 '05 #2
[Nick Coghlan]
> Hmm, it might be nice if there was a UserList.ListMixin that was the
> counterpart to UserDict.DictMixin

[Steven Bethard] I've thought this occasionally too. One of the tricky issues though is
that often you'd like to define __getitem__ for single items and have
ListMixin add the code for slices. I haven't figured out how to do this
cleanly yet...


All that is needed is a helper function and a two line idiom for calling it from
inside __getitem__:

def sliceit(self, sliceobj):
return [self[i] for i in xrange(*sliceobj.indices(len(self)))]

class AlphaList:
def __getitem__(self, i):
if isinstance(i, slice):
return sliceit(self, i)
return chr(i+64)
def __len__(self):
return 26

a = AlphaList()
print a[1], a[2], a[5]
print a[2:5]
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Matthew Barnes | last post by:
This may be a naive question, but since Python 2.3 added a handy little DictMixin class to its UserDict module it seems to me like UserList.ListMixin and maybe even UserString.StringMixin should...
3
by: Xif | last post by:
Hi I want to have control over all items added to a list. The first attempt was to subclass list and override its .append() method. Problem is, there are plenty of other ways the list can...
2
by: SammyBar | last post by:
Hi, I'm trying to bind a custom collection class to a data grid, following the guidelines from the article http://msdn.microsoft.com/msdnmag/issues/05/08/CollectionsandDataBinding/default.aspx....
7
by: who be dat? | last post by:
I need some help here. I'm creating a list on a page where the list is created from a dataset with two tables linked with a datarelation. The first table is a list of groups while the second...
3
by: Chris Newby | last post by:
I have a very simple custom control that derives from WebControls.Panel and implements INamingContainer. It appear that controls created as children of my custom control are having ViewState...
2
by: Dennis | last post by:
I have a form which has a ListView control named ListView1 added at design time. When I add items using the following code, they don't appear in the list view. However, if I create a ListView...
14
by: Rolf Welskes | last post by:
Hello, I have an ObjectDataSource which has as business-object a simple array of strings. No problem. I have an own (custom) control to which I give the DataSourceId and in the custom-control...
1
by: shapper | last post by:
Hello, I have a class where I created various controls. One of the controls have a property which is a generic list of WebControl. Then in web site page I have something like: Dim a As New...
2
by: =?Utf-8?B?SmFzb24gQmFybmV0dA==?= | last post by:
I've created a component that inherits from ComboBox. Wiithin its constructor, I've hardcoded some initial items that I'd like added. These items are of a custom class. When I add my control...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.