concise code (beginner)

Daniel Larsson daniel.j.larsson at gmail.com
Wed Sep 5 21:55:52 CEST 2007


On 9/5/07, Karthik Gurusamy <kar1107 at gmail.com> wrote:
>
> On Sep 5, 11:17 am, James Stroud <jstr... at mbi.ucla.edu> wrote:
> > bambam wrote:
> > > I have about 30 pages (10 * 3 pages each) of code like this
> > > (following). Can anyone suggest a more compact way to
> > > code the exception handling? If there is an exception, I need
> > > to continue the loop, and continue the list.
> >
> > > Steve.
> >
> > > -----------------------------------
> > > for dev in devs
> > >     try:
> > >         dev.read1()
> > >     except
> > >         print exception
> > >         remove dev from devs
> >
> > > for dev in devs
> > >     try:
> > >         dev.read2()
> >
> > [etc.]
> >
> > My keen sense of pattern recognition tells me that all of your read's
> > follow the same naming pattern--or was that just an accidental naming
> > coincidence on your part for the sake of example?
> >
> > for i in xrange(number_of_reads):
> >    for dev in devs:
> >      try:
> >        _reader = getattr(dev, 'read%d' % i)
> >        _reader()
> >      except Exception, e:
> >        print e
> >        devs.remove(dev)
>
> I see in many of the solutions suggested above, the devs sequence/
> iterator is being modified while iterating. I know it is not defined
> for interation over dictionary keys. Are they defined for other
> collections like lists?
>
> Karthik


You're  right, that's a bad thing. You should collect the "bad" devs in a
separate list, and remove them outside the loop.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070905/a2f2ea65/attachment.html>


More information about the Python-list mailing list