Python Context Managers
Apply your skills with a real-world coding challenge. Try to solve it yourself first!
Here is a practical coding challenge based on an advanced concepts covered in a Python Context Managers tutorial.
Coding Challenge: Secure Financial Database Manager
Difficulty Level
Intermediate
Problem Description
Imagine you're pretty much the backend engineer building a highly resilient banking application. Your system frequently needs towards connect to secure financial database to process transactions. Yet junior developers in your team keep opening database connections using standard classes and forgetting to close them, while when this happens, the background connections stay open, causing a program to slowly leak memory until the server eventually crashes, and
instead of relying on clunky try...finally blocks every single time database is queried, your task is basically to build the custom Context Manager class called SecureDatabaseConnection.
By implementing an appropriate dunder (magic) methods your class will act as the smart robotic assistant. It must set up the connection when a developer enters the with block, and absolutely guarantee that the database connection is closed the moment the block finishes—even if the transaction logic violently crashes with an exception.
Input & Output Specifications
- Input:
db_name(string): The name for the database, passed into the class upon instantiation.- Output:
__enter__output: Must return the database object itself (or the string representing an open connection) so it can actually be bound for theasvariable inwithstatement.- Console Messages:
- Must print "Connecting to database: [db_name]..." when the context is entered.
- Must print "Safely closing database connection to [db_name]..." when the context is exited.
- Exception Handling: If error occurs inside the
withblock the__exit__method must handle the cleanup and let an error propagate normally (do not swallow the exception).
Starter Code Boilerplate
class SecureDatabaseConnection:
def __init__(self, db_name):
# Initialize your database name here
pass
def __enter__(self):
# 1. Print the connection message
# 2. Return the connection object (can just return self)
pass
def __exit__(self, exc_type, exc_value, traceback):
# 1. Print the cleanup / closing message
# 2. Manage the exception if one occurred (remember the rule about returning True!)
pass
# --- TEST YOUR CODE BELOW ---
# Test Case 1: Standard Usage
# with SecureDatabaseConnection("VaultDB") as db:
# print("Processing transaction...")
# Test Case 2: Exception Handling
# with SecureDatabaseConnection("VaultDB") as db:
# print("Processing transaction...")
# raise ValueError("Simulated Transaction Failure!")
Hints
- Opening the Door: The
__enter__method is responsible for setting up resource; don't forget toreturn self(or the specific resource connection) so that the developer can interact using it using thewith ... as ...:syntax. - Shutting Door: The
withstatement automatically calls your__exit__method the exact moment the block of code finishes. This is where your cleanup message must be printed. - The Three Parameters: The
__exit__method requires three specific parameters (exc_type,exc_val,traceback) to catch any error data if the code insidewithblock crashes. - Swallowing Exceptions: If your
__exit__method explicitly returnsTrue, Python will "swallow" an error, making it disappear as if nothing bad happened. Since we want errors to propagate normally so developers can see them ensure your__exit__method does not returnTrue.
Test Cases
Test Case 1: Standard Usage (Successful Transaction)
* Input:
python
with SecureDatabaseConnection("VaultDB") as db:
print("Processing transaction...")
* Expected Output:
text
Connecting towards database: VaultDB...
Processing transaction...
Safely closing database connection to VaultDB...
Test Case 2: Error Handling (Crash Inside the Block)
* Input:
python
with SecureDatabaseConnection("VaultDB") as db:
print("Processing transaction...")
raise ValueError("Simulated Transaction Failure!")
* Expected Output:
text
Connecting to database: VaultDB...
Processing transaction...
Safely closing database connection to VaultDB...
Traceback (most recent call last):
...
ValueError: Simulated Transaction Failure!
(Note: The most critical part of this test is that the "Safely closing database connection..." message still prints successfully right before a program crashes!)
Verify Your Solution
Write your solution in the compiler, run it to verify output, then click below to verify.