forked from fluentpython/example-code-2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mirror_gen.py
79 lines (59 loc) · 1.71 KB
/
mirror_gen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""
A "mirroring" ``stdout`` context manager.
While active, the context manager reverses text output to
``stdout``::
# tag::MIRROR_GEN_DEMO_1[]
>>> from mirror_gen import looking_glass
>>> with looking_glass() as what: # <1>
... print('Alice, Kitty and Snowdrop')
... print(what)
...
pordwonS dna yttiK ,ecilA
YKCOWREBBAJ
>>> what
'JABBERWOCKY'
>>> print('back to normal')
back to normal
# end::MIRROR_GEN_DEMO_1[]
This exposes the context manager operation::
# tag::MIRROR_GEN_DEMO_2[]
>>> from mirror_gen import looking_glass
>>> manager = looking_glass() # <1>
>>> manager # doctest: +ELLIPSIS
<contextlib._GeneratorContextManager object at 0x...>
>>> monster = manager.__enter__() # <2>
>>> monster == 'JABBERWOCKY' # <3>
eurT
>>> monster
'YKCOWREBBAJ'
>>> manager # doctest: +ELLIPSIS
>...x0 ta tcejbo reganaMtxetnoCrotareneG_.biltxetnoc<
>>> manager.__exit__(None, None, None) # <4>
False
>>> monster
'JABBERWOCKY'
# end::MIRROR_GEN_DEMO_2[]
The decorated generator also works as a decorator:
# tag::MIRROR_GEN_DECO[]
>>> @looking_glass()
... def verse():
... print('The time has come')
...
>>> verse() # <1>
emoc sah emit ehT
>>> print('back to normal') # <2>
back to normal
# end::MIRROR_GEN_DECO[]
"""
# tag::MIRROR_GEN_EX[]
import contextlib
import sys
@contextlib.contextmanager # <1>
def looking_glass():
original_write = sys.stdout.write # <2>
def reverse_write(text): # <3>
original_write(text[::-1])
sys.stdout.write = reverse_write # <4>
yield 'JABBERWOCKY' # <5>
sys.stdout.write = original_write # <6>
# end::MIRROR_GEN_EX[]