## Example: Simple db manager class with context manager
class MyDBManager:
def __init__(self):
# our dummy database
self.some_db = {"id": [], "name": []}
# this method is called when entering the 'with' statement
def __enter__(self):
return self
# this method is called when exiting the 'with' block code
def __exit__(self, exc_type, exc_val, exc_tb):
# here we are clearing the database when exiting
self.some_db["id"] = []
self.some_db["name"] = []
# a function to add values to our db
def add(self, my_id, name):
self.some_db["id"].append(my_id)
self.some_db["name"].append(name)
# create a instance of our db class
db = MyDBManager()
# using the 'with' on our instance
with db as db_handler:
# add some values to our db
db_handler.add(3251, "bob")
db_handler.add(3252, "rob")
db_handler.add(3253, "job")
db_handler.add(3251, "tob")
# print the db data
print(db_handler.some_db) # {'id': [3251, 3252, 3253, 3251], \
# 'name': ['bob', 'rob', 'job', 'tob']}
# now to clear the db just get out of the indentation
# check the data in db
print(db.some_db) # {'id': [], 'name': []}
# as soon as we were out of the indentation, '__exit__()'
# was called automatically which cleared the data, try modifying this
# behaviour to remove duplicate entries