Understanding Context Managers in Python: Usage and Best Practices
☰Fullscreen
Table of Content:
-
A
Context Managerallows a programmer to perform required activities, automatically, while entering or exiting a Context. -
For example, opening a file, doing few file operations, and closing the file is manged using
Context Manageras shown below.
with open('sample.txt', 'w') as fp:
content = fp.read()
- The keyword
withis used in Python to enable a context manager. It automatically takes care of closing the file.
- Consider the following example, which tries to establish a connection to a database, perform few db operations and finally close the connection.
Example 1
import sqlite3
try:
dbConnection = sqlite3.connect('TEST.db')
cursor = dbConnection.cursor()
'''
Few db operations
...
'''
except Exception:
print('No Connection.')
finally:
dbConnection.close()
Example 2
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
...
'''