Python - Context Manager

Context Manager

Example with regular implementation
import sqlite3
try:
    dbConnection = sqlite3.connect('TEST.db')
    cursor = dbConnection.cursor()
    '''
    Few db operations
    ...
    '''
except Exception:
    print('No Connection.')
finally:
    dbConnection.close()

Example with Context Manager
import sqlite3
class DbConnect(object):
    def __init__(self, dbname):
        self.dbname = dbname
    def __enter__(self):
        self.dbConnection = sqlite3.connect(self.dbname)
        return self.dbConnection
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.dbConnection.close()
with DbConnect('TEST.db') as db:
    cursor = db.cursor()
    '''
   Few db operations
   ...
    '''

No comments:

Post a Comment