Sunday, 2 June 2013

With statement in Python

The with statement can be useful for writing reusable code. I have found especially useful when working with a database.

import MySQLdb as db

def getConnection():
    return db.connect(
        host = 'localhost',
        port = '3306',
        user = 'riz',
        passwd = 'password',
        db =  'blogdb'
    )

#Class that implements the with protocol
class Cursor():
    # method is called at the start of the with statement 
    def __enter__(self):
        conn = getConnection()
        self.cursor = conn.cursor()
        return self.cursor
    
    # method is called at the end of the with statement 
    # or if an exception is thrown within the with block
    def __exit__(self, type, value, traceback):
        self.cursor.close()
        if traceback:
            print "Type: ",type
            print "Value: ", value
            print "Trace: ", traceback
        return not traceback

 def getAllPosts():  
    with Cursor() as cursor:  # __enter__ called result is stored in cursor
        #you can use the cursor here as normal 
        cursor.execute('SELECT * FROM POSTS')
        return cursor.fetchall()

No comments:

Post a Comment