cython

Форк
0
/
withstat_py.py 
221 строка · 4.6 Кб
1
# mode: run
2

3
def typename(t):
4
    name = type(t).__name__
5
    return "<type '%s'>" % name
6

7

8
class MyException(Exception):
9
    pass
10

11

12
class ContextManager(object):
13
    def __init__(self, value, exit_ret = None):
14
        self.value = value
15
        self.exit_ret = exit_ret
16

17
    def __exit__(self, a, b, tb):
18
        print("exit %s %s %s" % (typename(a), typename(b), typename(tb)))
19
        return self.exit_ret
20

21
    def __enter__(self):
22
        print("enter")
23
        return self.value
24

25

26
def no_as():
27
    """
28
    >>> no_as()
29
    enter
30
    hello
31
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
32
    """
33
    with ContextManager("value"):
34
        print("hello")
35

36

37
def basic():
38
    """
39
    >>> basic()
40
    enter
41
    value
42
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
43
    """
44
    with ContextManager("value") as x:
45
        print(x)
46

47

48
def with_pass():
49
    """
50
    >>> with_pass()
51
    enter
52
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
53
    """
54
    with ContextManager("value") as x:
55
        pass
56

57

58
def with_return():
59
    """
60
    >>> print(with_return())
61
    enter
62
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
63
    value
64
    """
65
    with ContextManager("value") as x:
66
        return x
67

68

69
def with_break():
70
    """
71
    >>> print(with_break())
72
    enter
73
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
74
    a
75
    """
76
    for c in list("abc"):
77
        with ContextManager("value") as x:
78
            break
79
        print("FAILED")
80
    return c
81

82

83
def with_continue():
84
    """
85
    >>> print(with_continue())
86
    enter
87
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
88
    enter
89
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
90
    enter
91
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
92
    c
93
    """
94
    for c in list("abc"):
95
        with ContextManager("value") as x:
96
            continue
97
        print("FAILED")
98
    return c
99

100

101
def with_exception(exit_ret):
102
    """
103
    >>> with_exception(None)
104
    enter
105
    value
106
    exit <type 'type'> <type 'MyException'> <type 'traceback'>
107
    outer except
108
    >>> with_exception(True)
109
    enter
110
    value
111
    exit <type 'type'> <type 'MyException'> <type 'traceback'>
112
    """
113
    try:
114
        with ContextManager("value", exit_ret=exit_ret) as value:
115
            print(value)
116
            raise MyException()
117
    except:
118
        print("outer except")
119

120

121
def with_real_lock():
122
    """
123
    >>> with_real_lock()
124
    about to acquire lock
125
    holding lock
126
    lock no longer held
127
    """
128
    from threading import Lock
129
    lock = Lock()
130

131
    print("about to acquire lock")
132

133
    with lock:
134
        print("holding lock")
135

136
    print("lock no longer held")
137

138

139
def functions_in_with():
140
    """
141
    >>> f = functions_in_with()
142
    enter
143
    exit <type 'type'> <type 'MyException'> <type 'traceback'>
144
    outer except
145
    >>> f(1)[0]
146
    1
147
    >>> print(f(1)[1])
148
    value
149
    """
150
    try:
151
        with ContextManager("value") as value:
152
            def f(x): return x, value
153
            make = lambda x:x()
154
            raise make(MyException)
155
    except:
156
        print("outer except")
157
    return f
158

159

160
def multitarget():
161
    """
162
    >>> multitarget()
163
    enter
164
    1 2 3 4 5
165
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
166
    """
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))
169

170

171
def tupletarget():
172
    """
173
    >>> tupletarget()
174
    enter
175
    (1, 2, (3, (4, 5)))
176
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
177
    """
178
    with ContextManager((1, 2, (3, (4, 5)))) as t:
179
        print(t)
180

181

182
class GetManager(object):
183
    def get(self, *args):
184
        return ContextManager(*args)
185

186

187
def manager_from_expression():
188
    """
189
    >>> manager_from_expression()
190
    enter
191
    1
192
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
193
    enter
194
    2
195
    exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
196
    """
197
    with GetManager().get(1) as x:
198
        print(x)
199
    g = GetManager()
200
    with g.get(2) as x:
201
        print(x)
202

203
def manager_from_ternary(use_first):
204
    """
205
    >>> manager_from_ternary(True)
206
    enter
207
    exit <type 'type'> <type 'ValueError'> <type 'traceback'>
208
    >>> manager_from_ternary(False)
209
    enter
210
    exit <type 'type'> <type 'ValueError'> <type 'traceback'>
211
    In except
212
    """
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")
217
    try:
218
        with (cm1_getter if use_first else cm2_getter)():
219
            raise ValueError
220
    except ValueError:
221
        print("In except")
222

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.