1

I am currently making a module that makes coding databases with sqlite3 easier and one of my functions is as follows:

def fetch(cursor, tableName, target = "*", condition = None, fetchType = "all"): # Fetches data from a table in a database
    "Fetches data from a table in a database\nExecutes 'SELECT {target} FROM {tableName} WHERE {condition}' on the cursor\nExample: user1Name = fetch(cursor, 'tblUser', target = 'userName', condition = 'userId = 1', fetchType = 'one')"

    if condition != None: cursor.execute(f"SELECT {target} FROM {tableName} WHERE {condition}") # Selects values if there is a condition

    else: cursor.execute(f"SELECT {target} FROM {tableName}") # Selects targets if there is not a condition

    if fetchType == "all": return cursor.fetchall() # Fetches all values

    elif fetchType == "one": return cursor.fetchone() # Fetches one value

    else: raise Exception("Invalid fetchType.") # Raises an exception if the user is trying to use an invalid fetchType

I essentially want to find a way to make it so instead of calling var = fetch(cursor... I can call var = cursor.fetch(tableName... for ease of access and because I simply want to know how I would do this in future.

  • In order to call fetch as a function from cursor, you need to declare an object with fetch function defined. Look at [classes](https://docs.python.org/3/tutorial/classes.html) – scmanjarrez Jun 27 '21 at 22:40

1 Answers1

1

This is called monkey-patching, which is very common for dynamic languages. Find class of cursor (let's call it CursorClass), then monkey patch it in. The first parameter will act as self:

def fetch(cursor, table, ...)
    # cursor will act as self inside this functon
    ...

# Make sure that you do not override an
# existing attribute on CursorClass
CursorClass.fetch = fetch

# Then you can call fetch on the cursor
cursor = CursorClass(...)
cursor.fetch('TableName', ...)
Code Different
  • 90,614
  • 16
  • 144
  • 163