4
name = type(t).__name__
5
return "<type '%s'>" % name
8
class MyException(Exception):
12
class ContextManager(object):
13
def __init__(self, value, exit_ret = None):
15
self.exit_ret = exit_ret
17
def __exit__(self, a, b, tb):
18
print("exit %s %s %s" % (typename(a), typename(b), typename(tb)))
31
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
33
with ContextManager("value"):
42
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
44
with ContextManager("value") as x:
52
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
54
with ContextManager("value") as x:
60
>>> print(with_return())
62
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
65
with ContextManager("value") as x:
71
>>> print(with_break())
73
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
77
with ContextManager("value") as x:
85
>>> print(with_continue())
87
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
89
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
91
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
95
with ContextManager("value") as x:
101
def with_exception(exit_ret):
103
>>> with_exception(None)
106
exit <type 'type'> <type 'MyException'> <type 'traceback'>
108
>>> with_exception(True)
111
exit <type 'type'> <type 'MyException'> <type 'traceback'>
114
with ContextManager("value", exit_ret=exit_ret) as value:
118
print("outer except")
124
about to acquire lock
128
from threading import Lock
131
print("about to acquire lock")
134
print("holding lock")
136
print("lock no longer held")
139
def functions_in_with():
141
>>> f = functions_in_with()
143
exit <type 'type'> <type 'MyException'> <type 'traceback'>
151
with ContextManager("value") as value:
152
def f(x): return x, value
154
raise make(MyException)
156
print("outer except")
165
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
167
with ContextManager((1, 2, (3, (4, 5)))) as (a, b, (c, (d, e))):
168
print('%s %s %s %s %s' % (a, b, c, d, e))
176
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
178
with ContextManager((1, 2, (3, (4, 5)))) as t:
182
class GetManager(object):
183
def get(self, *args):
184
return ContextManager(*args)
187
def manager_from_expression():
189
>>> manager_from_expression()
192
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
195
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
197
with GetManager().get(1) as x:
203
def manager_from_ternary(use_first):
205
>>> manager_from_ternary(True)
207
exit <type 'type'> <type 'ValueError'> <type 'traceback'>
208
>>> manager_from_ternary(False)
210
exit <type 'type'> <type 'ValueError'> <type 'traceback'>
213
# This is mostly testing a parsing problem, hence the
214
# result of the ternary must be callable
215
cm1_getter = lambda: ContextManager("1", exit_ret=True)
216
cm2_getter = lambda: ContextManager("2")
218
with (cm1_getter if use_first else cm2_getter)():