cython

Форк
0
/
exceptionrefcount.pyx 
64 строки · 1.5 Кб
1
# mode: run
2

3
"""
4
>>> class SampleException(Exception): pass
5

6
>>> def assert_refcount(rc1, rc2, func):
7
...     # test ref-counts, but allow a bit of freedom
8
...     assert rc2 <= rc1 + 4, "%s, before: %d, after %d" % (
9
...         func.__name__, rc1, rc2)
10

11
>>> def run_test(repeat, test_func):
12
...     initial_refcount = get_refcount(SampleException)
13
...     for i in range(repeat):
14
...         try: raise SampleException
15
...         except:
16
...             refcount1 = get_refcount(SampleException)
17
...             test_func()
18
...             refcount2 = get_refcount(SampleException)
19
...
20
...             assert_refcount(refcount1, refcount2, test_func)
21
...             assert_refcount(initial_refcount, refcount2, test_func)
22
...         refcount3 = get_refcount(SampleException)
23
...         assert_refcount(refcount1, refcount3, test_func)
24
...         assert_refcount(initial_refcount, refcount3, test_func)
25

26
>>> run_test(50, test_no_exception_else)
27
>>> run_test(50, test_no_exception)
28
>>> run_test(50, test_exception)
29
>>> run_test(50, test_finally)
30
"""
31

32
cimport cython
33
from cpython.ref cimport PyObject, Py_REFCNT
34

35
@cython.binding(False)
36
@cython.always_allow_keywords(False)
37
def get_refcount(obj):
38
    return Py_REFCNT(obj)
39

40
def test_no_exception():
41
    try:
42
        a = 1+1
43
    except:
44
        pass
45

46
def test_no_exception_else():
47
    try:
48
        a = 1+1
49
    except:
50
        pass
51
    else:
52
        b = 1+1
53

54
def test_exception():
55
    try:
56
        raise TypeError
57
    except:
58
        pass
59

60
def test_finally():
61
    try:
62
        a = 1+1
63
    finally:
64
        b = 1+1
65

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

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

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

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