Differences between revisions 1 and 6 (spanning 5 versions)
Revision 1 as of 2020-02-11 19:55:43
Size: 1370
Comment:
Revision 6 as of 2023-01-07 04:01:52
Size: 1759
Comment:
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
A '''context manager''' is an object that forms a scope inside a `with` block. A '''context manager''' is an object that forms a scope inside a `with` block. This is useful for giving access to an externally-managed resource while gracefully handling errors.

See also [[Python/ContextLib|contextlib]], a module for working with context managers.

<<TableOfContents>>
Line 9: Line 13:
== Basic Example == == Example ==
Line 11: Line 15:
{{{#!highlight python {{{
Line 13: Line 17:
import pprint
from typing import *
from pprint import pprint
from types import TracebackType
Line 17: Line 21:
    """A reference to a database."""     def __init__(self, cursor: sqlite3.Cursor) -> None:
        self._cursor = cursor
Line 19: Line 24:
    def __init__(
        self,
        cursor: sqlite3.Cursor,
    ) -> None:
        self.curs = cursor
    def execute(self, cmd: str, vals: Tuple = tuple()) -> List:
        self._cursor.execute(cmd, vals)
        return self._cursor.fetchall()
Line 25: Line 28:
    def execute(
        self,
        cmd: str,
        vals: Tuple = tuple(),
    ) -> List:
        self.curs.execute(cmd, vals)
        return self.curs.fetchone()
class database_connection(object):
    def __init__(self, filename: str) -> None:
        self._connect = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES)
        self._cursor = self._connect.cursor()

    def __enter__(self) -> sqlite3.Cursor:
        return Database(self._cursor)

    def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> bool:
        self._connect.commit()
        self._cursor.close()
        self._connect.close()

with database_connection(":memory:") as db:
    db.execute("CREATE TABLE mytable (num INTEGER, name TEXT)")
    for n in range(10):
        db.execute("INSERT INTO mytable (num,name) VALUES (?,?)", (n,str(n)))
    data = db.execute("SELECT * FROM mytable")
    pprint(data)
}}}

----
Line 34: Line 52:
class open_db(object):
    """Context manager for sqlite3 DB."""
Line 37: Line 53:
    def __init__(
        self,
        filename: str,
    ) -> None:
        self.conn = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES)
        self.curs = self.conn.cursor()
== Definition ==
Line 44: Line 55:
    def __enter__(self) -> Database:
        return Database(self.curs)
A context manager needs to define an `__enter__` function and an `__exit__` function.
Line 47: Line 57:
    def __exit__(
        self,
        *exception: Any,
    ) -> None:
        self.conn.commit()
        self.curs.close()
        self.conn.close()


with open_db("my.sqlite") as db:
    db.execute("CREATE TABLE mytable (num INTEGER, name TEXT)")
    db.execute("INSERT INTO mytable (num,name) VALUES (?,?)", (1,2))
    data = db.execute("SELECT * FROM mytable")
    pprint.pprint(data)

}}}
The `__exit__` function is called if an error raises. To suppress errors, have it return `True`.

Python Context Manager

A context manager is an object that forms a scope inside a with block. This is useful for giving access to an externally-managed resource while gracefully handling errors.

See also contextlib, a module for working with context managers.


Example

import sqlite3
from pprint import pprint
from types import TracebackType

class Database(object):
    def __init__(self, cursor: sqlite3.Cursor) -> None:
        self._cursor = cursor

    def execute(self, cmd: str, vals: Tuple = tuple()) -> List:
        self._cursor.execute(cmd, vals)
        return self._cursor.fetchall()

class database_connection(object):
    def __init__(self, filename: str) -> None:
        self._connect = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES)
        self._cursor = self._connect.cursor()

    def __enter__(self) -> sqlite3.Cursor:
        return Database(self._cursor)

    def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> bool:
        self._connect.commit()
        self._cursor.close()
        self._connect.close()

with database_connection(":memory:") as db:
    db.execute("CREATE TABLE mytable (num INTEGER, name TEXT)")
    for n in range(10):
        db.execute("INSERT INTO mytable (num,name) VALUES (?,?)", (n,str(n)))
    data = db.execute("SELECT * FROM mytable")
    pprint(data)


Definition

A context manager needs to define an __enter__ function and an __exit__ function.

The __exit__ function is called if an error raises. To suppress errors, have it return True.


CategoryRicottone

Python/ContextManager (last edited 2023-01-07 04:01:52 by DominicRicottone)