|
Size: 1456
Comment:
|
Size: 1590
Comment:
|
| Deletions are marked like this. | Additions are marked like this. |
| Line 1: | Line 1: |
| ## page was renamed from PythonContextManager = Python Context Manager = |
## page was renamed from Python/ContextManagers = Python Context Managers = |
| Line 10: | Line 10: |
| == Basic Example == | == Example == |
| Line 12: | Line 12: |
| {{{#!highlight python | {{{ |
| Line 14: | Line 14: |
| import pprint from typing import * |
from pprint import pprint from types import TracebackType |
| Line 18: | Line 18: |
| """A reference to a database.""" | def __init__(self, cursor: sqlite3.Cursor) -> None: self._cursor = cursor |
| Line 20: | Line 21: |
| 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 26: | Line 25: |
| def execute( self, cmd: str, vals: Tuple = tuple(), ) -> List: self.curs.execute(cmd, vals) return self.curs.fetchall() class open_db(object): """Context manager for sqlite3 DB.""" def __init__( self, filename: str, ) -> None: self.conn = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES) self.curs = self.conn.cursor() |
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() |
| Line 46: | Line 31: |
| return Database(self.curs) | return Database(self._cursor) |
| Line 48: | Line 33: |
| def __exit__( self, *exception: Any, ) -> None: self.conn.commit() self.curs.close() self.conn.close() |
def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> bool: self._connect.commit() self._cursor.close() self._connect.close() |
| Line 56: | Line 38: |
with open_db(":memory:") as db: |
with database_connection(":memory:") as db: |
| Line 62: | Line 43: |
| pprint.pprint(data) | pprint(data) }}} |
| Line 64: | Line 46: |
| }}} | ---- == Usage == 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`. |
Python Context Managers
A context manager is an object that forms a scope inside a with block.
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)
Usage
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.
