Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

try/except in a loop

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


jmwebaze at gmail

May 2, 2012, 12:51 PM

Post #1 of 10 (482 views)
Permalink
try/except in a loop

I have multiple objects, where any of them can serve my purpose.. However
some objects might not have some dependencies. I can not tell before hand
if the all the dependencies exsit. What i want to is begin processing from
the 1st object, if no exception is raised, i am done.. if an exception is
raised, the next object is tried, etc Something like

objs = [... ]
try:
obj = objs[0]
obj.make()
except Exception, e:
try:
obj = objs[1]
obj.make()
except Exception, e:
try:
obj = objs[2]
obj.make()
except Exception, e:
continue

The problem is the length of the list of objs is variable... How can i do
this?



--
*Mob UG: +256 (0) 70 1735800 | NL +31 (0) 6 852 841 38 | Gtalk: jmwebaze |
skype: mwebazej | URL: www.astro.rug.nl/~jmwebaze

/* Life runs on code */*


ckaynor at zindagigames

May 2, 2012, 12:58 PM

Post #2 of 10 (469 views)
Permalink
Re: try/except in a loop [In reply to]

On Wed, May 2, 2012 at 12:51 PM, J. Mwebaze <jmwebaze [at] gmail> wrote:
> I have multiple objects, where any of them can serve my purpose.. However
> some objects might not have some dependencies. I can not tell before hand if
> the all the dependencies exsit. What i want to is begin processing from the
> 1st object, if no exception is raised, i am done.. if an exception is
> raised, the next object is tried, etc  Something like
>
> objs = [... ]
> try:
>   obj = objs[0]
>   obj.make()
> except Exception, e:
>   try:
>       obj = objs[1]
>       obj.make()
>   except Exception, e:
>      try:
>         obj = objs[2]
>         obj.make()
>      except Exception, e:
>        continue
>
> The problem is the length of the list of objs is variable... How can i do
> this?


for obj in objs:
try:
obj.make()
except Exception:
continue
else:
break
else:
raise RuntimeError('No object worked')

>
>
>
> --
> Mob UG: +256 (0) 70 1735800 | NL +31 (0) 6 852 841 38 | Gtalk: jmwebaze |
> skype: mwebazej | URL: www.astro.rug.nl/~jmwebaze
>
> /* Life runs on code */
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


bahamutzero8825 at gmail

May 2, 2012, 1:07 PM

Post #3 of 10 (469 views)
Permalink
Re: try/except in a loop [In reply to]

Why wouldn't a for loop work? If something works, you can break out,
otherwise continue.

working_obj = None
for obj in iterable:
try:
obj.do_something()
working_obj = obj
break
except:
continue

--
CPython 3.3.0a3 | Windows NT 6.1.7601.17790
--
http://mail.python.org/mailman/listinfo/python-list


bahamutzero8825 at gmail

May 2, 2012, 1:10 PM

Post #4 of 10 (471 views)
Permalink
Re: try/except in a loop [In reply to]

Forgot to add that all this is covered in the tutorial in the official docs:
http://docs.python.org/tutorial/controlflow.html#for-statements

--
CPython 3.3.0a3 | Windows NT 6.1.7601.17790
--
http://mail.python.org/mailman/listinfo/python-list


ramit.prasad at jpmorgan

May 2, 2012, 1:12 PM

Post #5 of 10 (468 views)
Permalink
RE: try/except in a loop [In reply to]

> > I have multiple objects, where any of them can serve my purpose..
> However
> > some objects might not have some dependencies. I can not tell before
> hand if
> > the all the dependencies exsit. What i want to is begin processing from
> the
> > 1st object, if no exception is raised, i am done.. if an exception is
> > raised, the next object is tried, etc Something like
> >
> > objs = [... ]
> > try:
> > obj = objs[0]
> > obj.make()
> > except Exception, e:
> > try:
> > obj = objs[1]
> > obj.make()
> > except Exception, e:
> > try:
> > obj = objs[2]
> > obj.make()
> > except Exception, e:
> > continue
> >
> > The problem is the length of the list of objs is variable... How can i
> do
> > this?
>
>
> for obj in objs:
> try:
> obj.make()
> except Exception:
> continue
> else:
> break
> else:
> raise RuntimeError('No object worked')


I think you misunderstand the else clauses.

>>> for obj in [ 1,2,3,4 ]:
... try:
... print obj
... except Exception:
... print 'EXCEPTION'
... else:
... print 'NO EXCEPTION'
... else:
... print 'NO OBJECTS'
...
1
NO EXCEPTION
2
NO EXCEPTION
3
NO EXCEPTION
4
NO EXCEPTION
NO OBJECTS


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
--
http://mail.python.org/mailman/listinfo/python-list


ckaynor at zindagigames

May 2, 2012, 1:27 PM

Post #6 of 10 (468 views)
Permalink
Re: try/except in a loop [In reply to]

On Wed, May 2, 2012 at 1:12 PM, Prasad, Ramit <ramit.prasad [at] jpmorgan> wrote:
>> > I have multiple objects, where any of them can serve my purpose..
>> However
>> > some objects might not have some dependencies. I can not tell before
>> hand if
>> > the all the dependencies exsit. What i want to is begin processing from
>> the
>> > 1st object, if no exception is raised, i am done.. if an exception is
>> > raised, the next object is tried, etc  Something like
>> >
>> > objs = [... ]
>> > try:
>> >   obj = objs[0]
>> >   obj.make()
>> > except Exception, e:
>> >   try:
>> >       obj = objs[1]
>> >       obj.make()
>> >   except Exception, e:
>> >      try:
>> >         obj = objs[2]
>> >         obj.make()
>> >      except Exception, e:
>> >        continue
>> >
>> > The problem is the length of the list of objs is variable... How can i
>> do
>> > this?
>>
>>
>> for obj in objs:
>>     try:
>>         obj.make()
>>     except Exception:
>>         continue
>>     else:
>>         break
>> else:
>>     raise RuntimeError('No object worked')
>
>
> I think you misunderstand the else clauses.
>
>>>> for obj in [ 1,2,3,4 ]:
> ...     try:
> ...         print obj
> ...     except Exception:
> ...         print 'EXCEPTION'
> ...     else:
> ...         print 'NO EXCEPTION'
> ... else:
> ...     print 'NO OBJECTS'
> ...
> 1
> NO EXCEPTION
> 2
> NO EXCEPTION
> 3
> NO EXCEPTION
> 4
> NO EXCEPTION
> NO OBJECTS

You left out the break in the try clause's else that I had. That break
statement causes the for loop to exit early if there is no exception,
and thus the for loop's else clause does not run:

>>> for obj in [ 1,2,3,4 ]:
... try:
... print obj
... except Exception:
... print 'EXCEPTION'
... else:
... print 'NO EXCEPTION'
... break
... else:
... print 'NO OBJECTS'
...
1
NO EXCEPTION

>
>
> Ramit
>
>
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
>
> --
>
> This email is confidential and subject to important disclaimers and
> conditions including on offers for the purchase or sale of
> securities, accuracy and completeness of information, viruses,
> confidentiality, legal privilege, and legal entity disclaimers,
> available at http://www.jpmorgan.com/pages/disclosures/email.
> --
> http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


ramit.prasad at jpmorgan

May 2, 2012, 2:00 PM

Post #7 of 10 (467 views)
Permalink
RE: try/except in a loop [In reply to]

> >> for obj in objs:
> >> try:
> >> obj.make()
> >> except Exception:
> >> continue
> >> else:
> >> break
> >> else:
> >> raise RuntimeError('No object worked')
> >
> >
> > I think you misunderstand the else clauses.
> >
> >>>> for obj in [ 1,2,3,4 ]:
> > ... try:
> > ... print obj
> > ... except Exception:
> > ... print 'EXCEPTION'
> > ... else:
> > ... print 'NO EXCEPTION'
> > ... else:
> > ... print 'NO OBJECTS'
> > ...
> > 1
> > NO EXCEPTION
> > 2
> > NO EXCEPTION
> > 3
> > NO EXCEPTION
> > 4
> > NO EXCEPTION
> > NO OBJECTS
>
> You left out the break in the try clause's else that I had. That break
> statement causes the for loop to exit early if there is no exception,
> and thus the for loop's else clause does not run:
>
> >>> for obj in [ 1,2,3,4 ]:
> ... try:
> ... print obj
> ... except Exception:
> ... print 'EXCEPTION'
> ... else:
> ... print 'NO EXCEPTION'
> ... break
> ... else:
> ... print 'NO OBJECTS'
> ...
> 1
> NO EXCEPTION

Whoops, you are right. My apologies Chris!

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
--
http://mail.python.org/mailman/listinfo/python-list


jeanmichel at sequans

May 3, 2012, 6:27 AM

Post #8 of 10 (459 views)
Permalink
Re: try/except in a loop [In reply to]

Chris Kaynor wrote:
> On Wed, May 2, 2012 at 12:51 PM, J. Mwebaze <jmwebaze [at] gmail> wrote:
>
>> I have multiple objects, where any of them can serve my purpose.. However
>> some objects might not have some dependencies. I can not tell before hand if
>> the all the dependencies exsit. What i want to is begin processing from the
>> 1st object, if no exception is raised, i am done.. if an exception is
>> raised, the next object is tried, etc Something like
>>
>> objs = [... ]
>> try:
>> obj = objs[0]
>> obj.make()
>> except Exception, e:
>> try:
>> obj = objs[1]
>> obj.make()
>> except Exception, e:
>> try:
>> obj = objs[2]
>> obj.make()
>> except Exception, e:
>> continue
>>
>> The problem is the length of the list of objs is variable... How can i do
>> this?
>>
>
>
> for obj in objs:
> try:
> obj.make()
> except Exception:
> continue
> else:
> break
> else:
> raise RuntimeError('No object worked')
>
>
For the record, an alternative solution without try block:

candidates = [obj for obj in objs if hasattr(obj, 'make') and
callable(obj.make)]
if candidates:
candidates[0].make()


JM
--
http://mail.python.org/mailman/listinfo/python-list


__peter__ at web

May 3, 2012, 6:57 AM

Post #9 of 10 (456 views)
Permalink
Re: try/except in a loop [In reply to]

Jean-Michel Pichavant wrote:

> Chris Kaynor wrote:
>> On Wed, May 2, 2012 at 12:51 PM, J. Mwebaze <jmwebaze [at] gmail> wrote:
>>
>>> I have multiple objects, where any of them can serve my purpose..
>>> However some objects might not have some dependencies. I can not tell
>>> before hand if the all the dependencies exsit. What i want to is begin
>>> processing from the 1st object, if no exception is raised, i am done..
>>> if an exception is
>>> raised, the next object is tried, etc Something like
>>>
>>> objs = [... ]
>>> try:
>>> obj = objs[0]
>>> obj.make()
>>> except Exception, e:
>>> try:
>>> obj = objs[1]
>>> obj.make()
>>> except Exception, e:
>>> try:
>>> obj = objs[2]
>>> obj.make()
>>> except Exception, e:
>>> continue
>>>
>>> The problem is the length of the list of objs is variable... How can i
>>> do this?
>>>
>>
>>
>> for obj in objs:
>> try:
>> obj.make()
>> except Exception:
>> continue
>> else:
>> break
>> else:
>> raise RuntimeError('No object worked')
>>
>>
> For the record, an alternative solution without try block:

Hmm, it's not sufficient that the method exists, it should succeed, too.

class Obj:
def make(self):
raise Exception("I'm afraid I can't do that")
objs = [Obj()]

> candidates = [.obj for obj in objs if hasattr(obj, 'make') and
> callable(obj.make)]
> if candidates:
> candidates[0].make()

It is often a matter of taste, but I tend to prefer EAFP over LBYL.

--
http://mail.python.org/mailman/listinfo/python-list


jeanmichel at sequans

May 3, 2012, 7:54 AM

Post #10 of 10 (456 views)
Permalink
Re: try/except in a loop [In reply to]

Peter Otten wrote:
> Jean-Michel Pichavant wrote:
>
>
>> Chris Kaynor wrote:
>>
>>> On Wed, May 2, 2012 at 12:51 PM, J. Mwebaze <jmwebaze [at] gmail> wrote:
>>>
>>>
>>>> I have multiple objects, where any of them can serve my purpose..
>>>> However some objects might not have some dependencies. I can not tell
>>>> before hand if the all the dependencies exsit. What i want to is begin
>>>> processing from the 1st object, if no exception is raised, i am done..
>>>> if an exception is
>>>> raised, the next object is tried, etc Something like
>>>>
>>>> objs = [... ]
>>>> try:
>>>> obj = objs[0]
>>>> obj.make()
>>>> except Exception, e:
>>>> try:
>>>> obj = objs[1]
>>>> obj.make()
>>>> except Exception, e:
>>>> try:
>>>> obj = objs[2]
>>>> obj.make()
>>>> except Exception, e:
>>>> continue
>>>>
>>>> The problem is the length of the list of objs is variable... How can i
>>>> do this?
>>>>
>>>>
>>> for obj in objs:
>>> try:
>>> obj.make()
>>> except Exception:
>>> continue
>>> else:
>>> break
>>> else:
>>> raise RuntimeError('No object worked')
>>>
>>>
>>>
>> For the record, an alternative solution without try block:
>>
>
> Hmm, it's not sufficient that the method exists, it should succeed, too.
>
> class Obj:
> def make(self):
> raise Exception("I'm afraid I can't do that")
> objs = [Obj()]
>
>
>> candidates = [.obj for obj in objs if hasattr(obj, 'make') and
>> callable(obj.make)]
>> if candidates:
>> candidates[0].make()
>>
>
> It is often a matter of taste, but I tend to prefer EAFP over LBYL.
>
>
Could be that the OP did its job by calling the make method if it
exists. If the method raises an exception, letting it through is a
viable option if you cannot handle the exception.
Additionaly, having a method not raising any exception is not a criteria
for success, for instance

def make(self):
return 42

will surely fail to do what the OP is expecting.

By the way on a unrelated topic, using try blocks to make the code
"robust" is never a good idea, I hope the OP is not try to do that.

JM

--
http://mail.python.org/mailman/listinfo/python-list

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.