472,986 Members | 2,705 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Customize the effect of enumerate()?

Can I make enumerate(myObject) act differently?

class A(object):
def __getitem__(self, item):
if item 0:
return self.sequence[item-1]
elif item < 0:
return self.sequence[item]
elif item == 0:
raise IndexError, "Index 0 is not valid."
else:
raise IndexError, "Invalid Index."
def __iter__(self): return iter(self.sequence)

Why the funny behavior, you ask? For my class A, it doesn't make sense
to number everything the standard programming way. Of course, if
someone uses enumerate, it's going to number the items the same way as
ever. Is there any way to modify that behavior, any special function to
set? There doesn't appear to be, according to the docs, but it never
hurts to make sure.

Oct 21 '06 #1
8 1376
"Dustan" <Du**********@gmail.comwrites:
Can I make enumerate(myObject) act differently?
No.
Why the funny behavior, you ask? For my class A, it doesn't make sense
to number everything the standard programming way.
Add an enumerate method to the class then, that does what you want.
Maybe dict.iteritems would be a better example to follow.
Oct 21 '06 #2

Paul Rubin wrote:
"Dustan" <Du**********@gmail.comwrites:
Can I make enumerate(myObject) act differently?

No.
Why the funny behavior, you ask? For my class A, it doesn't make sense
to number everything the standard programming way.

Add an enumerate method to the class then, that does what you want.
Maybe dict.iteritems would be a better example to follow.
That's what I thought. Thanks anyway!

Oct 21 '06 #3
Dustan wrote:
Can I make enumerate(myObject) act differently?

class A(object):
def __getitem__(self, item):
if item 0:
return self.sequence[item-1]
elif item < 0:
return self.sequence[item]
elif item == 0:
raise IndexError, "Index 0 is not valid."
else:
raise IndexError, "Invalid Index."
def __iter__(self): return iter(self.sequence)
That final else clause is a little funny... What kind of indices are
you expecting that will be neither less than zero, greater than zero,
or equal to zero?
Why the funny behavior, you ask? For my class A, it doesn't make sense
to number everything the standard programming way. Of course, if
someone uses enumerate, it's going to number the items the same way as
ever. Is there any way to modify that behavior, any special function to
set? There doesn't appear to be, according to the docs, but it never
hurts to make sure.
You can write your own enumerate function and then bind that to the
name 'enumerate'.

Oct 22 '06 #4
Simon Forman wrote:
Dustan wrote:
>>Can I make enumerate(myObject) act differently?

class A(object):
def __getitem__(self, item):
if item 0:
return self.sequence[item-1]
elif item < 0:
return self.sequence[item]
elif item == 0:
raise IndexError, "Index 0 is not valid."
else:
raise IndexError, "Invalid Index."
def __iter__(self): return iter(self.sequence)


That final else clause is a little funny... What kind of indices are
you expecting that will be neither less than zero, greater than zero,
or equal to zero?
Good defensive programming albeit of a somewhat extreme nature. Should
one of the tests be removed at a later date the else clause will trap
occurrences of the no-longer handled case.
>
>>Why the funny behavior, you ask? For my class A, it doesn't make sense
to number everything the standard programming way. Of course, if
someone uses enumerate, it's going to number the items the same way as
ever. Is there any way to modify that behavior, any special function to
set? There doesn't appear to be, according to the docs, but it never
hurts to make sure.


You can write your own enumerate function and then bind that to the
name 'enumerate'.
Yes, but if you do you had better make sure that it gives the standard
behavior for normal uses.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Oct 23 '06 #5

Simon Forman wrote:
Dustan wrote:
Can I make enumerate(myObject) act differently?

class A(object):
def __getitem__(self, item):
if item 0:
return self.sequence[item-1]
elif item < 0:
return self.sequence[item]
elif item == 0:
raise IndexError, "Index 0 is not valid."
else:
raise IndexError, "Invalid Index."
def __iter__(self): return iter(self.sequence)

That final else clause is a little funny... What kind of indices are
you expecting that will be neither less than zero, greater than zero,
or equal to zero?
I'm not 'expecting' anything to reach that clause, but it is a good
catch-all if I forget something or have a bug somewhere.
Why the funny behavior, you ask? For my class A, it doesn't make sense
to number everything the standard programming way. Of course, if
someone uses enumerate, it's going to number the items the same way as
ever. Is there any way to modify that behavior, any special function to
set? There doesn't appear to be, according to the docs, but it never
hurts to make sure.

You can write your own enumerate function and then bind that to the
name 'enumerate'.
Except that my program is supposed to be treated as a module with tools
to do certain things. I certainly can't control whether a 3rd party
programmer uses "import myModule" or "from myModule import *".

I haven't gotten around to doing it yet, but I'm pretty sure I'm
planning on taking Paul Rubin's course of action - make a method
(iteritems or similar) that will enumerate correctly.

Oct 23 '06 #6
"Dustan" wrote:
Except that my program is supposed to be treated as a module with tools
to do certain things. I certainly can't control whether a 3rd party
programmer uses "import myModule" or "from myModule import *".
anything can happen if people use "from import *" in the wrong way, so that's
not much of an argument, really.

</F>

Oct 23 '06 #7
On Sun, 22 Oct 2006 15:56:16 -0700, Simon Forman wrote:
Dustan wrote:
>Can I make enumerate(myObject) act differently?

class A(object):
def __getitem__(self, item):
if item 0:
return self.sequence[item-1]
elif item < 0:
return self.sequence[item]
elif item == 0:
raise IndexError, "Index 0 is not valid."
else:
raise IndexError, "Invalid Index."
def __iter__(self): return iter(self.sequence)

That final else clause is a little funny... What kind of indices are
you expecting that will be neither less than zero, greater than zero,
or equal to zero?
Possible a NaN value? Maybe a class instance with strange comparison
methods?

Personally, I don't like the error message. "Invalid index" doesn't really
tell the caller what went wrong and why it is an invalid index. If I were
programming that defensively, I'd write:

if item 0:
return self.sequence[item-1]
elif item < 0:
return self.sequence[item]
elif item == 0:
raise IndexError, "Index 0 is not valid."
else:
print repr(item)
raise ThisCanNeverHappenError("Congratulations! You've discovered "
"a bug that can't possibly occur. Contact the program author for "
"your reward.")

I know some programmers hate "Can't happen" tests and error messages, but
if you are going to test for events that can't possibly happen, at least
deal with the impossible explicitly!
--
Steven.

Oct 23 '06 #8
Fredrik Lundh wrote:
"Dustan" wrote:
Except that my program is supposed to be treated as a module with tools
to do certain things. I certainly can't control whether a 3rd party
programmer uses "import myModule" or "from myModule import *".

anything can happen if people use "from import *" in the wrong way, so that's
not much of an argument, really.

</F>
My argument was that if they use "import myModule", overriding
enumerate() wouldn't work. So "from myModule import *" would work
nicely, but not the former. Given that, I'm not getting your rebuttal,
or whatever it is.
Steven D'Aprano wrote:
On Sun, 22 Oct 2006 15:56:16 -0700, Simon Forman wrote:
That final else clause is a little funny... What kind of indices are
you expecting that will be neither less than zero, greater than zero,
or equal to zero?

Possible a NaN value? Maybe a class instance with strange comparison
methods?

Personally, I don't like the error message. "Invalid index" doesn't really
tell the caller what went wrong and why it is an invalid index. If I were
programming that defensively, I'd write:

if item 0:
return self.sequence[item-1]
elif item < 0:
return self.sequence[item]
elif item == 0:
raise IndexError, "Index 0 is not valid."
else:
print repr(item)
raise ThisCanNeverHappenError("Congratulations! You've discovered "
"a bug that can't possibly occur. Contact the program author for "
"your reward.")

I know some programmers hate "Can't happen" tests and error messages, but
if you are going to test for events that can't possibly happen, at least
deal with the impossible explicitly!
I certainly can't argue with that logic; I might even go so far as to
agree with you and start raising impossible errors with this kind of
explicitness.

What reward should I offer? ;-)

Oct 23 '06 #9

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

Similar topics

5
by: Pekka Niiranen | last post by:
Hi, I have Perl code looping thru lines in the file: line: while (<INFILE>) { ... $_ = do something ... if (/#START/) { # Start inner loop
5
by: HL | last post by:
Hi, I need to enumerate windows and find the sum of the rect of all the windows of a specific application. In C++, I use the APIs - 'EnumWindows , GetWindowRect and UnionRect to accomplish the...
1
by: smichr | last post by:
I see that there is a thread of a similar topic that was posted recently ( enumerate with a start index ) but thought I would start a new thread since what I am suggesting is a little different. ...
4
by: Fred | last post by:
Hello, datagrids have GridLines, BorderWidth, BorderColor, ItemStyle.CssClass, ShowFooter ... properties, which can be used to customize the way they look when printed, how does one achieve the...
6
by: Gregory Petrosyan | last post by:
Hello! I have a question for the developer of enumerate(). Consider the following code: for x,y in coords(dots): print x, y When I want to iterate over enumerated sequence I expect this to...
2
by: eight02645999 | last post by:
hi, i am using python 2.1. Can i use the code below to simulate the enumerate() function in 2.3? If not, how to simulate in 2.1? thanks from __future__ import generators def...
21
by: James Stroud | last post by:
I think that it would be handy for enumerate to behave as such: def enumerate(itrbl, start=0, step=1): i = start for it in itrbl: yield (i, it) i += step This allows much more flexibility...
12
by: Danny Colligan | last post by:
In the following code snippet, I attempt to assign 10 to every index in the list a and fail because when I try to assign number to 10, number is a deep copy of the ith index (is this statement...
0
by: Sky | last post by:
I have an Access 2003 front-end database with custom toolbars. The toolbars work fine. One annoying feature is that at the far right edge of each custom toolbar there a small dropdown arrow....
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
3
SueHopson
by: SueHopson | last post by:
Hi All, I'm trying to create a single code (run off a button that calls the Private Sub) for our parts list report that will allow the user to filter by either/both PartVendor and PartType. On...

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.