简体   繁体   中英

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

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

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() 

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.

You should use

try:
    element = location.objects.order_by('-id').filter(name__id=idRef)[0]
except IndexError:
    pass

You make it a bit hard to tell what you're doing. The code simply checks if you get any rows from the query, by looking at the first element and catching the IndexError.

I would write it in a way that makes this intention much clearer:

for locationName in locationGroup:
    idRef = locationName.id
    rows = location.objects.order_by('-id').filter(name__id=idRef)
    if rows: # if we have rows do stuff otherwise continue
         element = rows[0]
         ...

In this case you can use get which makes it even more clearer:

for locationName in locationGroup:
    idRef = locationName.id
    try:
         element = location.objects.get(name__id=idRef)
    except location.DoesNotExist:
         pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM