0

I'm running into an error when I try to instantiate an object from a cursor in SQLite and I've exhausted my research and couldn't find a solution.

Premise: I cannot use SqlAlchemy or anything of that sorts.

Assumption: The database (SQLite) works, it contains a table named table_cars, and the table is populated with data in its single column: name.

So, I have a class lets say:

class Car():
   def __init__(self, name):
      self.name = name

   @classmethod
      def from_cursor(cls, c):
         car = cls(c(0))
         # this line breaks when called from the function below.

And I also have a db module, with the following function:

def get_cars_from_db():
   sql = 'SELECT * FROM table_cars;'
   conn = get_conn()
   cur = conn.cursor()
   cur.execute(sql)
   data = cur.fetchall()
   # at this point, if i print the cursor, I can see all data, so far so good.

   cars = [Car.from_cursor(c) for c in data]
   # the line above causes the code to break

   return cars

The code breaks with the following error:

TypeError: 'tuple' object is not callable

What am I doing wrong here?

4
  • 1
    In list comprehension of get_cars_from_db(), c is a row of the db select result. In from_cursor() you are using c(0) which means c is callable and you are calling it with parameter 0 Commented May 26, 2021 at 12:35
  • so how do I extract the data from the cursor to parse it into the object? Commented May 26, 2021 at 12:37
  • 1
    In from_cursor(), c is a tuple with same number of entries as column in your table_cars. You can fetch the name from that tuple and then create Car object Commented May 26, 2021 at 12:40
  • now I realise that I need to use [] to access an index of a tuple, not (). Silly me. so the correct syntax would be car = cls(c[0]) Commented May 26, 2021 at 12:44

1 Answer 1

2

You can use cls(c[0]) or cls(*c) to unpack tuple to function arguments. It's also worth to specify an exact order of your columns in query.

select name from table_cars
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.