11

I am opening mysql connection in the main function and use that connection in multiple functions called by the main function.

Is there anything wrong with passing cursor from main function instead of passing the connection?

I.e.:

Pass in cursor from main function

def main():
    conn = pymysql.connect(...)
    with conn as cursor:
        func1(cursor)
        func2(cursor)
    conn.close()

def func1(cursor):
    cursor.execute('select ...')

def func2(cursor):
    cursor.execute('insert ...')

Pass in connection from main function

def main():
    conn = pymysql.connect(...)
    func1(conn)
    func2(conn)
    conn.close()

def func1(conn):
    with conn as cursor:
        cursor.execute('select ...')

def func2(conn):
    with conn as cursor:
        cursor.execute('insert ...')
Pavel Chernikov
  • 2,186
  • 1
  • 20
  • 37

1 Answers1

8

The answer comes from Law of Demeter: Pass cursor.

This also leads to a slightly shorter code. In this case, it's pretty trivial, but sometimes it may be a lot (e.g., passing a database name vs. passing a cursor).

maaartinus
  • 44,714
  • 32
  • 161
  • 320