Reputation: 359
I have this method in a class which takes a value from a database call, (the table in the database has a key: catId and another field)
def getCat(self):
''' devuelve el numero de la categoria
'''
a = self.datab.select('categorias',where='catName = $nombre', vars=dict(nombre=self.nombre))
a= a.list()
return a[0].catId
context: i use this to make some categorization in my web content, so i want to return the value wich will join to the content table in the database.
So if i give to it a self.nombre wich is a string stored in a database row i'll ever take one element from the database.
The python interpreter gives me this error:
File "C:\xampp\htdocs\webpy\functions.py", line 26, in getCat return a[0].catId IndexError: list index out of range
127.0.0.1:51463 - - [05/Apr/2013 13:29:22] "HTTP/1.1 GET /c/\css\style.css" - 500 Internal Server Error
but the web gives out the information correctly, I have no problem with the web output but i wish to know why is this error in the indexing a[0]
I made the a.list() in order to simplify some uses of the itterbetter
complete error mesage in the idle interpreter:
0.0 (1): SELECT catName FROM categorias ORDER BY catId ASC 127.0.0.1:51900 - - [05/Apr/2013 16:46:31] "HTTP/1.1 GET /c/" - 200 OK 0.0 (1): SELECT * FROM categorias WHERE catName = '\\css\\style.css' Traceback (most recent call last): File "C:\Python27\lib\site-packages\web\application.py", line 236, in process return self.handle() File "C:\Python27\lib\site-packages\web\application.py", line 227, in handle return self._delegate(fn, self.fvars, args) File "C:\Python27\lib\site-packages\web\application.py", line 409, in _delegate return handle_class(cls) File "C:\Python27\lib\site-packages\web\application.py", line 384, in handle_class return tocall(*args) File "C:\xampp\htdocs\webpy\code.py", line 32, in GET seleccion = functions.categoria(db,cat) File "C:\xampp\htdocs\webpy\functions.py", line 16, in __init__ self.n = self.getCat() #calculo del numero de la categoria PROBLEMAS File "C:\xampp\htdocs\webpy\functions.py", line 26, in getCat return a[0].catId IndexError: list index out of range
Upvotes: 0
Views: 360
Reputation: 2867
You need to do proper error handling, you can either do:
try:
a[0].catId
except IndexError as ie:
# Do some stuff here
except:
# either re-raise the exception or pass it silently
Or you can do:
return a and a[0].catId or [] # This will check for empty list
It depends on your implementation choice.
Upvotes: 3
Reputation: 309891
That's the exact error message you would get if you tried to get an item from an empty list:
>>> [][0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
So it appears that a.list()
is returning an empty list.
Upvotes: 1