Get around raising IndexError

26,129

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.

Share:
26,129
moutone
Author by

moutone

Updated on March 20, 2020

Comments

  • moutone
    moutone about 4 years

    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 ?