summaryrefslogtreecommitdiff
path: root/tests/run/__getattribute__.pyx
blob: e7af8b03363c1194d632087f2f7a7bd99b27f2e4 (plain)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# mode: run

# __getattribute__ and __getattr__ special methods for a single class.


cdef class just_getattribute:
    """
    >>> a = just_getattribute()
    >>> a.called
    1
    >>> a.called
    2
    >>> a.bar
    'bar'
    >>> a.called
    4
    >>> try: a.invalid
    ... except AttributeError: pass
    ... else: print("NOT RAISED!")
    >>> a.called
    6
    """
    cdef readonly int called
    def __getattribute__(self,n):
        self.called += 1
        if n == 'bar':
            return n
        elif n == 'called':
            return self.called
        else:
            raise AttributeError


cdef class just_getattr:
    """
    >>> a = just_getattr()
    >>> a.called
    0
    >>> a.called
    0
    >>> a.foo
    10
    >>> a.called
    0
    >>> a.bar
    'bar'
    >>> a.called
    1
    >>> try: a.invalid
    ... except AttributeError: pass
    ... else: print("NOT RAISED!")
    >>> a.called
    2
    """
    cdef readonly int called
    cdef readonly int foo
    def __init__(self):
        self.foo = 10
    def __getattr__(self,n):
        self.called += 1
        if n == 'bar':
            return n
        else:
            raise AttributeError


cdef class both:
    """
    >>> a = both()
    >>> (a.called_getattr, a.called_getattribute)
    (0, 2)
    >>> a.foo
    10
    >>> (a.called_getattr, a.called_getattribute)
    (0, 5)
    >>> a.bar
    'bar'
    >>> (a.called_getattr, a.called_getattribute)
    (1, 8)
    >>> try: a.invalid
    ... except AttributeError: pass
    ... else: print("NOT RAISED!")
    >>> (a.called_getattr, a.called_getattribute)
    (2, 11)
    """
    cdef readonly int called_getattribute
    cdef readonly int called_getattr
    cdef readonly int foo
    def __init__(self):
        self.foo = 10

    def __getattribute__(self,n):
        self.called_getattribute += 1
        if n == 'foo':
            return self.foo
        elif n == 'called_getattribute':
            return self.called_getattribute
        elif n == 'called_getattr':
            return self.called_getattr
        else:
            raise AttributeError

    def __getattr__(self,n):
        self.called_getattr += 1
        if n == 'bar':
            return n
        else:
            raise AttributeError