cython

Форк
0
/
cyfunction.pyx 
411 строк · 8.9 Кб
1
# cython: binding=True
2
# mode: run
3
# tag: cyfunction
4

5

6
def inspect_isroutine():
7
    """
8
    >>> inspect_isroutine()
9
    True
10
    """
11
    import inspect
12
    return inspect.isroutine(inspect_isroutine)
13

14

15
def inspect_isfunction():
16
    """
17
    >>> inspect_isfunction()
18
    False
19
    False
20
    """
21
    import inspect, types
22
    print isinstance(inspect_isfunction, types.FunctionType)
23
    return inspect.isfunction(inspect_isfunction)
24

25

26
def inspect_isbuiltin():
27
    """
28
    >>> inspect_isbuiltin()
29
    False
30
    False
31
    """
32
    import inspect, types
33
    print isinstance(inspect_isfunction, types.BuiltinFunctionType)
34
    return inspect.isbuiltin(inspect_isbuiltin)
35

36

37
def inspect_signature(a, b, c=123, *, d=234):
38
    """
39
    >>> sig = inspect_signature(1, 2)
40
    >>> list(sig.parameters)
41
    ['a', 'b', 'c', 'd']
42
    >>> sig.parameters['c'].default == 123
43
    True
44
    >>> sig.parameters['d'].default == 234
45
    True
46
    """
47
    import inspect
48
    return inspect.signature(inspect_signature)
49

50

51
# def test___signature__(a, b, c=123, *, d=234):
52
#     """
53
#     >>> sig = test___signature__(1, 2)
54
#     >>> list(sig.parameters)
55
#     ['a', 'b', 'c', 'd']
56
#     >>> sig.parameters['c'].default == 123
57
#     True
58
#     >>> sig.parameters['d'].default == 234
59
#     True
60
#     """
61
#     return inspect_signature.__signature__
62

63

64
def test_dict():
65
    """
66
    >>> test_dict.foo = 123
67
    >>> test_dict.__dict__
68
    {'foo': 123}
69
    >>> test_dict.__dict__ = {'bar': 321}
70
    >>> test_dict.__dict__
71
    {'bar': 321}
72
    >>> test_dict.func_dict
73
    {'bar': 321}
74
    """
75

76
def test_name():
77
    """
78
    >>> test_name.__name__
79
    'test_name'
80
    >>> test_name.func_name
81
    'test_name'
82
    >>> test_name.__name__ = 123 #doctest:+ELLIPSIS
83
    Traceback (most recent call last):
84
    TypeError: __name__ must be set to a ... object
85
    >>> test_name.__name__ = 'foo'
86
    >>> test_name.__name__
87
    'foo'
88
    """
89

90
def test_doc():
91
    """
92
    >>> del test_doc.__doc__
93
    >>> test_doc.__doc__
94
    >>> test_doc.__doc__ = 'docstring'
95
    >>> test_doc.__doc__
96
    'docstring'
97
    >>> test_doc.func_doc
98
    'docstring'
99
    """
100

101

102
def test_hash():
103
    """
104
    >>> d = {test_hash: 123}
105
    >>> test_hash in d
106
    True
107
    >>> d[test_hash]
108
    123
109
    >>> hash(test_hash) == hash(test_hash)
110
    True
111
    """
112

113

114
def test_closure():
115
    """
116
    >>> test_closure.func_closure is None
117
    True
118
    """
119

120
def test_globals():
121
    """
122
    >>> test_globals.func_globals is not None
123
    True
124
    >>> 'test_globals' in test_globals.func_globals or test_globals.func_globals
125
    True
126
    >>> 'test_name' in test_globals.func_globals or test_globals.func_globals
127
    True
128
    >>> 'not there' not in test_globals.func_globals or test_globals.func_globals
129
    True
130
    >>> try: test_globals.func_globals = {}
131
    ... except (AttributeError, TypeError): pass
132
    ... else: assert 0, 'FAILED'
133
    """
134

135
def test_reduce():
136
    """
137
    >>> import pickle
138
    >>> pickle.loads(pickle.dumps(test_reduce))()
139
    'Hello, world!'
140
    """
141
    return 'Hello, world!'
142

143
def test_method(self):
144
    return self
145

146
class BindingTest:
147
    """
148
    >>> BindingTest.test_method = test_method
149
    >>> BindingTest.test_method() #doctest:+ELLIPSIS
150
    Traceback (most recent call last):
151
    TypeError: ...
152
    >>> BindingTest().test_method()
153
    <BindingTest instance>
154
    """
155
    def __repr__(self):
156
        return '<BindingTest instance>'
157

158

159
def codeof(func):
160
    return func.__code__
161

162
def varnamesof(func):
163
    code = codeof(func)
164
    varnames = code.co_varnames
165
    return varnames
166

167
def namesof(func):
168
    code = codeof(func)
169
    names = code.co_names
170
    return names
171

172
def cy_no_arg():
173
    l = m = 1
174
def cy_one_arg(a):
175
    l = m = 1
176
def cy_two_args(x, b):
177
    l = m = 1
178
def cy_default_args(x=1, b=2):
179
    l = m = 1
180

181
def test_code():
182
    """
183
    >>> def no_arg(): l = m = 1
184
    >>> def one_arg(a): l = m = 1
185
    >>> def two_args(x, b): l = m = 1
186
    >>> def default_args(x=1, b=2): l = m = 1
187

188
    >>> codeof(no_arg).co_argcount
189
    0
190
    >>> codeof(cy_no_arg).co_argcount
191
    0
192
    >>> print(codeof(no_arg).co_name)
193
    no_arg
194
    >>> print(codeof(cy_no_arg).co_name)
195
    cy_no_arg
196
    >>> namesof(no_arg)
197
    ()
198
    >>> codeof(cy_no_arg).co_names
199
    ()
200
    >>> varnamesof(no_arg)
201
    ('l', 'm')
202
    >>> codeof(cy_no_arg).co_varnames
203
    ('l', 'm')
204

205
    >>> codeof(one_arg).co_argcount
206
    1
207
    >>> codeof(cy_one_arg).co_argcount
208
    1
209
    >>> print(codeof(one_arg).co_name)
210
    one_arg
211
    >>> print(codeof(cy_one_arg).co_name)
212
    cy_one_arg
213
    >>> namesof(one_arg)
214
    ()
215
    >>> codeof(cy_one_arg).co_names
216
    ()
217
    >>> varnamesof(one_arg)
218
    ('a', 'l', 'm')
219
    >>> codeof(cy_one_arg).co_varnames
220
    ('a', 'l', 'm')
221

222
    >>> codeof(two_args).co_argcount
223
    2
224
    >>> codeof(cy_two_args).co_argcount
225
    2
226
    >>> namesof(two_args)
227
    ()
228
    >>> codeof(cy_two_args).co_names
229
    ()
230
    >>> varnamesof(two_args)
231
    ('x', 'b', 'l', 'm')
232
    >>> codeof(cy_two_args).co_varnames
233
    ('x', 'b', 'l', 'm')
234

235
    >>> codeof(default_args).co_argcount
236
    2
237
    >>> codeof(cy_default_args).co_argcount
238
    2
239
    >>> namesof(default_args)
240
    ()
241
    >>> codeof(cy_default_args).co_names
242
    ()
243
    >>> varnamesof(default_args)
244
    ('x', 'b', 'l', 'm')
245
    >>> codeof(cy_default_args).co_varnames
246
    ('x', 'b', 'l', 'm')
247
    """
248

249

250
def test_annotations(a: "test", b: "other" = 2, c: 123 = 4) -> "ret":
251
    """
252
    >>> isinstance(test_annotations.__annotations__, dict)
253
    True
254
    >>> sorted(test_annotations.__annotations__.items())
255
    [('a', "'test'"), ('b', "'other'"), ('c', '123'), ('return', "'ret'")]
256

257
    >>> def func_b(): return 42
258
    >>> def func_c(): return 99
259
    >>> inner = test_annotations(1, func_b, func_c)
260
    >>> sorted(inner.__annotations__.items())
261
    [('return', 'c()'), ('x', "'banana'"), ('y', 'b()')]
262

263
    >>> inner.__annotations__ = {234: 567}
264
    >>> inner.__annotations__
265
    {234: 567}
266
    >>> inner.__annotations__ = None
267
    >>> inner.__annotations__
268
    {}
269
    >>> inner.__annotations__ = 321
270
    Traceback (most recent call last):
271
    TypeError: __annotations__ must be set to a dict object
272
    >>> inner.__annotations__
273
    {}
274

275
    >>> inner = test_annotations(1, func_b, func_c)
276
    >>> sorted(inner.__annotations__.items())
277
    [('return', 'c()'), ('x', "'banana'"), ('y', 'b()')]
278
    >>> inner.__annotations__['abc'] = 66
279
    >>> sorted(inner.__annotations__.items())
280
    [('abc', 66), ('return', 'c()'), ('x', "'banana'"), ('y', 'b()')]
281

282
    >>> inner = test_annotations(1, func_b, func_c)
283
    >>> sorted(inner.__annotations__.items())
284
    [('return', 'c()'), ('x', "'banana'"), ('y', 'b()')]
285
    """
286
    def inner(x: "banana", y: b()) -> c():
287
        return x,y
288
    return inner
289

290

291
def add_one(func):
292
    "Decorator to add 1 to the last argument of the function call"
293
    def inner(*args):
294
        args = args[:-1] + (args[-1] + 1,)
295
        return func(*args)
296
    return inner
297

298
@add_one
299
def test_decorated(x):
300
    """
301
    >>> test_decorated(0)
302
    1
303
    """
304
    return x
305

306
@add_one
307
@add_one
308
def test_decorated2(x):
309
    """
310
    >>> test_decorated2(0)
311
    2
312
    """
313
    return x
314

315

316
cdef class TestDecoratedMethods:
317
    @add_one
318
    def test(self, x):
319
        """
320
        >>> TestDecoratedMethods().test(0)
321
        1
322
        """
323
        return x
324

325
    @add_one
326
    @add_one
327
    def test2(self, x):
328
        """
329
        >>> TestDecoratedMethods().test2(0)
330
        2
331
        """
332
        return x
333

334
    def test_calls(self, x):
335
        """
336
        >>> TestDecoratedMethods().test_calls(2)
337
        25
338
        """
339
        return self.test(x) + self.test2(x*10)
340

341

342
cdef class TestUnboundMethodCdef:
343
    """
344
    >>> C = TestUnboundMethodCdef
345
    >>> C.meth is C.__dict__["meth"]
346
    True
347
    >>> TestUnboundMethodCdef.meth()  # doctest:+ELLIPSIS
348
    Traceback (most recent call last):
349
    TypeError: ...
350
    """
351
    def meth(self): pass
352

353

354
class TestUnboundMethod:
355
    """
356
    >>> C = TestUnboundMethod
357
    >>> C.meth is C.__dict__["meth"]
358
    True
359
    >>> TestUnboundMethod.meth()  # doctest:+ELLIPSIS
360
    Traceback (most recent call last):
361
    TypeError: ...
362
    """
363
    def meth(self): pass
364

365

366
class TestStaticmethod(object):
367
    """
368
    >>> x = TestStaticmethod()
369
    >>> x.staticmeth(42)
370
    42
371
    >>> x.staticmeth.__get__(42)()
372
    42
373
    """
374
    @staticmethod
375
    def staticmeth(arg): return arg
376

377

378
cdef class TestOptimisedBuiltinMethod:
379
    """
380
    >>> obj = TestOptimisedBuiltinMethod()
381
    >>> obj.append(2)
382
    3
383
    >>> obj.call(2)
384
    4
385
    >>> obj.call(3, obj)
386
    5
387
    """
388
    def append(self, arg):
389
        print(arg+1)
390

391
    def call(self, arg, obj=None):
392
        (obj or self).append(arg+1)  # optimistically optimised => uses fast fallback method call
393

394

395
def do_nothing(f):
396
    """Dummy decorator for `test_firstlineno_decorated_function`"""
397
    return f
398

399

400
@do_nothing
401
@do_nothing
402
def test_firstlineno_decorated_function():
403
    """
404
    check that `test_firstlineno_decorated_function` starts 5 lines below `do_nothing`
405

406
    >>> test_firstlineno_decorated_function()
407
    5
408
    """
409
    l1 = do_nothing.__code__.co_firstlineno
410
    l2 = test_firstlineno_decorated_function.__code__.co_firstlineno
411
    return l2 - l1
412

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

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

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

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