473,804 Members | 2,116 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.ListMi xin that was the
counterpart to UserDict.DictMi xin


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 1325
Steven Bethard wrote:
Nick Coghlan wrote:
> Hmm, it might be nice if there was a UserList.ListMi xin that was the
> counterpart to UserDict.DictMi xin


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):
"""Prototyp e ListMixin, exploring slice interface and semantics"""
def __getitem__(sel f, index):
if isinstance(inde x, 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(l en(self))
except TypeError:
raise TypeError, "unsized object"

try:
getter = self.__getsingl eitem__
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.__getsingl eitem__(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(sta rt)
args.append(sto p)
if step:
if step < 1:
raise ValueError, "slicing an iterable requires step >=1"
args.append(ste p)

iterator = itertools.islic e(*args)
if isinstance(inde x, 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(ProtoList Mixin):
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(ProtoListM ixin):
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.ListMi xin that was the
> counterpart to UserDict.DictMi xin

[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(*sliceob j.indices(len(s elf)))]

class AlphaList:
def __getitem__(sel f, 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
1824
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 have followed (although I'm not sure how useful a StringMixin class would really be). I'm just curious. Is there a reason these classes weren't included? Is anybody looking into this for Python 2.4? Should I submit a patch? Matthew Barnes
3
1595
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 have items added to it - e.g. extend, insert - and theyr'e not at all affected by the changes I made to append.
2
2768
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. The problem is the article is in VisualBasic. I already get the collection to be recognized as a Data Source by the IDE. It populated the DataGrid correctly from the fields on the items object of the collection, but I can't get the DataGrid to...
7
2085
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 table is a list of items in that group. I want to show these items in what would basically look a lot like a tree view. I decided to just show everything in a placeholder control on an aspx form. First, I display a groupname from the first table...
3
1869
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 problems. For example, suppose I create a ListBox control as a child of my custom control, attach a SelectedIndexChanged event handler to it, and bind its data in the Page_Load event handler only if the current request is not a post back. I load the...
2
443
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 control in code and add it to the form, it works. Why don't the items show up in the ListView that I added at desgn time. ' Create three items and three sets of subitems for each item. Dim item1 As New ListViewItem("item1", 0) ' Place a check...
14
14662
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 so I get the ObjectDataSource. No problem ..... ObjectDataSource src = .... //is ok i have it
1
1350
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 MyNamespace.ListItem a.WebControls.Add(tbName) a.WebControls.Add(lLabel)
2
1223
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 to a Form, the code-behind file contains code for each item. This seems unecessary and causes items to be added more than once (first, because of my ComboBox constructor; again, because of the code-behind items). I suspect that there may be a...
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10604
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10354
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10359
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9177
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6870
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4314
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.