I'm working on a simple decorator that creates and manages a database cursor. The goal is to 'inject' the cursor as the first argument of the function, but not expose it to the caller.
import psycopg2 @needsNewCursor def findItem(cursor, item_id): cursor.execute('SELECT name FROM items WHERE id = %s', [item_id]) item_result = cursor.fetchone() # ... return item # caller only needs to know about the ID findItem(1234)
def needsNewCursor(func): def decorator(*args, **kargs): print 'Creating new cursor' # This is slightly different in the final code, but I'm only # concerned about how I'm dealing with decorators, at the moment cursor = createDefaultCursor() if cursor: with cursor: # Pass the cursor in as the 1st param return func(cursor, *args, **kargs) # Give the function a chance to deal with fails return func(None, *args, **kargs) # QUESTION: Is this enough? decorator.__name__ = func.__name__ return decorator
Is this a good approach?