Skip to content

Commit 88abcd8

Browse files
committed
add contextlib samples
1 parent 0643083 commit 88abcd8

3 files changed

Lines changed: 42 additions & 0 deletions

File tree

py3/context/do_closing.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
from contextlib import contextmanager
5+
6+
@contextmanager
7+
def closing(fname):
8+
f = None
9+
try:
10+
f = open(fname, 'r')
11+
yield f
12+
finally:
13+
if f:
14+
f.close()
15+
16+
with closing('test.txt') as f:
17+
print(f.read())

py3/context/do_suppress.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import os
5+
6+
from contextlib import suppress
7+
8+
with suppress(FileNotFoundError):
9+
os.remove('tempfile.1')
10+
os.remove('tempfile.2')
11+
os.remove('tempfile.3')

py3/context/do_with.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
from contextlib import contextmanager
5+
6+
@contextmanager
7+
def log(name):
8+
print('[%s] start...' % name)
9+
yield
10+
print('[%s] end.' % name)
11+
12+
with log('DEBUG'):
13+
print('Hello, world!')
14+
print('Hello, Python!')

0 commit comments

Comments
 (0)