|
Size: 1409
Comment:
|
Size: 1456
Comment:
|
| Deletions are marked like this. | Additions are marked like this. |
| Line 1: | Line 1: |
| ## page was renamed from PythonContextManager |
Python Context Manager
A context manager is an object that forms a scope inside a with block.
Basic Example
1 import sqlite3
2 import pprint
3 from typing import *
4
5 class Database(object):
6 """A reference to a database."""
7
8 def __init__(
9 self,
10 cursor: sqlite3.Cursor,
11 ) -> None:
12 self.curs = cursor
13
14 def execute(
15 self,
16 cmd: str,
17 vals: Tuple = tuple(),
18 ) -> List:
19 self.curs.execute(cmd, vals)
20 return self.curs.fetchall()
21
22
23 class open_db(object):
24 """Context manager for sqlite3 DB."""
25
26 def __init__(
27 self,
28 filename: str,
29 ) -> None:
30 self.conn = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES)
31 self.curs = self.conn.cursor()
32
33 def __enter__(self) -> sqlite3.Cursor:
34 return Database(self.curs)
35
36 def __exit__(
37 self,
38 *exception: Any,
39 ) -> None:
40 self.conn.commit()
41 self.curs.close()
42 self.conn.close()
43
44
45 with open_db(":memory:") as db:
46 db.execute("CREATE TABLE mytable (num INTEGER, name TEXT)")
47 for n in range(10):
48 db.execute("INSERT INTO mytable (num,name) VALUES (?,?)", (n,str(n)))
49 data = db.execute("SELECT * FROM mytable")
50 pprint.pprint(data)
