"I have a bunch of python methods that follow this pattern:"
This is confusing.
Either you have a bunch of functions, or you have a bunch of methods of a class.
Bunch of Functions.
Do this instead.
class SQLFunction( object ):
def __init__( self, connection ):
self.connection = connection
def __call__( self, args=None ):
self.cursor= self.connection.cursor()
self.run( args )
self.cursor.commit()
self.cursor.close()
class DeleteSession( SQLFunction ):
def run( self, args ):
self.cursor.execute( "statement" )
delete_session = DeleteSession( connection )
Your function declarations are two lines longer, but essentially the same.
You can do func1( args )
because it's a callable object. The rest of
your program should remain unchanged.
Bunch of Methods in One Class.
class SomeClass( object ):
def __init__( self, connection ):
self.connection= connection
def sql_execute( self, statement, args= None )
self.cursor= self.connection.cursor()
self.cursor.execute( statement, args if args is not None else [] )
self.connection.commit()
self.cursor.close()
def delete_session( self ):
self.sql_execute( "statement" )
All your methods can look like delete_session and make use of a common sql_execute
method.