Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get around raising IndexError

My code is as follows :

for p in qs:
    set = None
    try:
        set = p.property.property_locations.all()
    except IndexError:
        pass

    if set:

Problem is that when set is none it still throws IndexError from this part of django.db.models.query:

try:
    qs = self._clone()
    qs.query.set_limits(k, k + 1)
    return list(qs)[0] 
except self.model.DoesNotExist, e:
    raise IndexError(e.args)

How to stop system from throwing this error and continuing to next element in for loop ?

like image 258
moutone Avatar asked Mar 02 '11 11:03

moutone


People also ask

How do I bypass list index out of range?

“List index out of range” error occurs in Python when we try to access an undefined element from the list. The only way to avoid this error is to mention the indexes of list elements properly.

How to deal with IndexError Python?

The Python IndexError: list index out of range can be fixed by making sure any elements accessed in a list are within the index range of the list. This can be done by using the range() function along with the len() function.

How do I get IndexError?

You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.

What do you mean by IndexError exception?

The IndexError exception in Python means that you are trying to access an index that doesn't exist. For example you are trying to access the 5th index of a list, but there are only 4 elements present. It is part of the LookupError Exception class.


1 Answers

In any case, there are two mistakes in your code:

  1. set is a builtin (as you can see from SO's syntax highlighting), so by giving your variable that name you're shadowing the builtin for no purpose, which is at least bad practice, and likely to cause issues later in the code.
  2. The canonical way to check if set is not None is by writing: if set is not None

Better yet, the canonical way to write that code snippet is:

try:
    [code that might raise an exception]
except Error:
    [code that handles the exception]
else:
    [code that executes when no exception was raised]

(substitute Error for the actual exception, of course)

That way you don't even have to check 'set' at that point.

like image 183
Don Joe Avatar answered Oct 20 '22 23:10

Don Joe