Skip to content

Latest commit

 

History

History
46 lines (30 loc) · 1.48 KB

20231212064259.md

File metadata and controls

46 lines (30 loc) · 1.48 KB

The power of context managers

Context Managers, a must-use 🐍 Python feature 😍

Here's why they're awesome:

• Resource Management: Automate setup/teardown for cleaner, leak-proof code.

• Error Handling: Manage exceptions elegantly, ensuring resource release.

• Code Clarity: with statements define clear resource usage scope, boosting readability.

Most know them for file handling, but they shine in other areas too, like managing database connections:

import sqlite3

class DatabaseConnection:
    def __init__(self, db_file):
        self.db_file = db_file
        self.connection = None

    def __enter__(self):
        self.connection = sqlite3.connect(self.db_file)
        return self.connection

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.connection:
            self.connection.close()


with DatabaseConnection('my_database.db') as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM my_table")
    results = cursor.fetchall()
    print(results)
# The connection is automatically closed here, even if an error occurs

Note there are two ways to define Python context managers:

• Class-Based: Implement a class with enter and exit special (dunder) methods, as shown in the previous example. Great for complex scenarios.

• Function-Based: Utilize contextlib module's @contextmanager decorator and write a function with a yield statement. More lightweight and straightforward for simpler tasks.

#contextmanager #contextlib