If you have a lot of functions connecting to the database, how do you do it so you don’t 1) pass a lot of arguments to each function 2) don’t establish (and close) a new connection each time. In pythonic pseudocode
main():
    db = …
    host = …
    username = …
    password = …
    some_function(db, host, username, password)
some_function(db, host, username, password):
   try:
   con = psycopg2.connect("dbname='{}' user='{}' password='{}' host='{}'".format(db, username, password, host))
   cur = con.cursor()
   cur.execute("SELECT * FROM {}.{};".format(schema, ‘myTable’))
   function2(cur.fetchall(),db, host, username, password)
…
    except:
        …
Function2(db, host, username, password):
   try:
     con = psycopg2.connect("dbname='{}' user='{}' password='{}' host='{}'".format(db, username, password, host))
     cur = con.cursor()
     cur.execute("SELECT * FROM {}.{};".format(schema, ‘otherTable’))
     function3(cur.fetchall(),db, host, username, password)
     …
    except:
        …
It’s unfortunate that some_function() and function2() are almost exactly the same (though the … inside would be different). I’m wondering how can I extract this code to reduce redundancy? At the very least how do I reduce the function signatures with db, host, username, password?
I thought of putting these as global variables so at least I wouldn't have to pass the variables to each function that needs the database.
 
     
    