Home > Software engineering >  python function parameter control
python function parameter control

Time:07-22

def getBooks(self,name):
        query = "SELECT * FROM books"
        self.cursor.execute(query)
        books = self.cursor.fetchall()
        return books

I have a function called "getBooks", and this function is actually a combination of 2 functions. one function must work without taking the 'name' parameter, the other must work by taking the 'name' parameter because i have to change the sql template according to the 'name' parameter. how can i provide that?

CodePudding user response:

You can specify a default parameter of name to be None, and then treat the variable according to its type:

def getBooks(self,name=None):
    if name is None:
        ...
    else:
        ...

CodePudding user response:

All you have to do is provide a default value None for the name and check in the query's code if it actually is a null value or not:

def getBooks(self, name = None):
    query = "SELECT * FROM books WHERE name = ? OR ? IS NULL"
    self.cursor.execute(query, (name, name))
    books = self.cursor.fetchall()
    return books

or:

def getBooks(self, name = None):
    query = "SELECT * FROM books WHERE name IS COALESCE(?, name)"
    self.cursor.execute(query, (name,))
    books = self.cursor.fetchall()
    return books

In both queries, if you call getBooks() then all the rows of the table will be returned.

  • Related