Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "continue" the Pythonic way to escape from a try catch block?

Tags:

python

django

I am new to django and thought of doing to simple django application to learn more about it, In one of the places in code I had to pick locationName and getting elements that matched same id as locationName in a table. When I started wondering is continue the most pythonic way to escape a for-loop?

Code in question is given below :

for locationName in locationGroup:
    idRef = locationName.id
    try:
        element = location.objects.order_by('-id').filter(name__id=idRef)[0]
    except IndexError:
        continue
like image 326
Shashank Singh Avatar asked Dec 06 '22 13:12

Shashank Singh


2 Answers

If there's some code you don't want getting executed after the except clause, continue is perfectly valid, otherwise some might find pass more suitable.

for x in range(y):
    try:
        do_something()
    except SomeException:
        continue
    # The following line will not get executed for the current x value if a SomeException is raised
    do_another_thing() 

for x in range(y):
    try:
        do_something()
    except SomeException:
        pass
    # The following line will get executed regardless of whether SomeException is thrown or not
    do_another_thing() 
like image 64
shanyu Avatar answered Dec 31 '22 13:12

shanyu


That's exactly what the continue/break keywords are for, so yes, that's the simplest and most pythonic way of doing it.

There should be one-- and preferably only one --obvious way to do it.

like image 44
pcalcao Avatar answered Dec 31 '22 15:12

pcalcao