cython

Форк
0
/
type_inference.pyx 
885 строк · 21.5 Кб
1
# cython: infer_types = True
2
# cython: language_level=3
3

4
# Also see type_inference_ll2.pyx for the same tests with language_level=2
5

6
cimport cython
7
from cython cimport typeof, infer_types
8
from cpython cimport bool
9

10
assert typeof(1 / 2) in ('long', 'double')
11
IS_LANGUAGE_LEVEL_3 = typeof(1 / 2) == 'double'
12

13
##################################################
14
# type inference tests in 'full' mode (infer_types=True)
15

16
cdef class MyType:
17
    pass
18

19
def simple():
20
    """
21
    >>> simple()
22
    """
23
    i = 3
24
    assert typeof(i) == "long", typeof(i)
25
    x = 1.41
26
    assert typeof(x) == "double", typeof(x)
27
    xptr = &x
28
    assert typeof(xptr) == "double *", typeof(xptr)
29
    xptrptr = &xptr
30
    assert typeof(xptrptr) == "double **", typeof(xptrptr)
31
    b = b"abc"
32
    assert typeof(b) == "bytes object", typeof(b)
33
    s = "abc"
34
    assert typeof(s) == "str object", typeof(s)
35
    u = u"xyz"
36
    assert typeof(u) == "str object", typeof(u)
37
    L = [1,2,3]
38
    assert typeof(L) == "list object", typeof(L)
39
    t = (4,5,6,())
40
    assert typeof(t) == "tuple object", typeof(t)
41
    t2 = (4, 5.0, 6)
42
    assert typeof(t2) == "(long, double, long)", typeof(t)
43

44
def builtin_types():
45
    """
46
    >>> builtin_types()
47
    """
48
    b = bytes()
49
    assert typeof(b) == "bytes object", typeof(b)
50
    s = str()
51
    assert typeof(s) == "str object", typeof(u)
52
    u = unicode()  # legacy name is still available
53
    assert typeof(u) == "str object", typeof(u)
54
    L = list()
55
    assert typeof(L) == "list object", typeof(L)
56
    t = tuple()
57
    assert typeof(t) == "tuple object", typeof(t)
58
    d = dict()
59
    assert typeof(d) == "dict object", typeof(d)
60
    B = bool()
61
    assert typeof(B) == "bool", typeof(B)
62

63
def slicing():
64
    """
65
    >>> slicing()
66
    """
67
    b = b"abc"
68
    assert typeof(b) == "bytes object", typeof(b)
69
    b1 = b[1:2]
70
    assert typeof(b1) == "bytes object", typeof(b1)
71
    b2 = b[1:2:2]
72
    assert typeof(b2) == "bytes object", typeof(b2)
73

74
    u = u"xyz"
75
    assert typeof(u) == "str object", typeof(u)
76
    u1 = u[1:2]
77
    assert typeof(u1) == "str object", typeof(u1)
78
    u2 = u[1:2:2]
79
    assert typeof(u2) == "str object", typeof(u2)
80

81
    s = "xyz"
82
    assert typeof(s) == "str object", typeof(s)
83
    s1 = s[1:2]
84
    assert typeof(s1) == "str object", typeof(s1)
85
    s2 = s[1:2:2]
86
    assert typeof(s2) == "str object", typeof(s2)
87

88
    L = [1,2,3]
89
    assert typeof(L) == "list object", typeof(L)
90
    L1 = L[1:2]
91
    assert typeof(L1) == "list object", typeof(L1)
92
    L2 = L[1:2:2]
93
    assert typeof(L2) == "list object", typeof(L2)
94

95
    t = (4,5,6,())
96
    assert typeof(t) == "tuple object", typeof(t)
97
    t1 = t[1:2]
98
    assert typeof(t1) == "tuple object", typeof(t1)
99
    t2 = t[1:2:2]
100
    assert typeof(t2) == "tuple object", typeof(t2)
101

102

103
def indexing():
104
    """
105
    >>> indexing()
106
    """
107
    b = b"abc"
108
    assert typeof(b) == "bytes object", typeof(b)
109
    b1 = b[1]
110
    assert typeof(b1) == "Python object", typeof(b1)
111

112
    u = u"xyz"
113
    assert typeof(u) == "str object", typeof(u)
114
    u1 = u[1]
115
    assert typeof(u1) == "Py_UCS4", typeof(u1)
116

117
    s = "xyz"
118
    assert typeof(s) == "str object", typeof(s)
119
    s1 = s[1]
120
    assert typeof(s1) == "Py_UCS4", typeof(s1)
121

122
    L = [1,2,3]
123
    assert typeof(L) == "list object", typeof(L)
124
    L1 = L[1]
125
    assert typeof(L1) == "Python object", typeof(L1)
126

127
    t = (4,5,())
128
    assert typeof(t) == "tuple object", typeof(t)
129
    t1 = t[1]
130
    assert typeof(t1) == "long", typeof(t1)
131

132
    t2 = ('abc', 'def', 'ghi')
133
    assert typeof(t2) == "tuple object", typeof(t2)
134
    t2_1 = t2[1]
135
    assert typeof(t2_1) == "str object", typeof(t2_1)
136
    t2_2 = t2[t[0]-3]
137
    assert typeof(t2_2) == "str object", typeof(t2_2)
138

139
    t5 = (b'abc', 'def', u'ghi')
140
    t5_0 = t5[0]
141
    assert typeof(t5_0) == "bytes object", typeof(t5_0)
142
    t5_1 = t5[1]
143
    assert typeof(t5_1) == "str object", typeof(t5_1)
144
    t5_2 = t5[2]
145
    assert typeof(t5_2) == "str object", typeof(t5_2)
146
    t5_3 = t5[t[0]-3]
147
    assert typeof(t5_3) == "Python object", typeof(t5_3)
148

149

150
def multiple_assignments():
151
    """
152
    >>> multiple_assignments()
153
    """
154
    a = 3
155
    a = 4
156
    a = 5
157
    assert typeof(a) == "long", typeof(a)
158
    b = a
159
    b = 3.1
160
    b = 3.14159
161
    assert typeof(b) == "double", typeof(b)
162
    c = a
163
    c = b
164
    c = [1,2,3]
165
    assert typeof(c) == "Python object", typeof(c)
166
    d = b'abc'
167
    d = bytes()
168
    d = bytes(b'xyz')
169
    d = None
170
    assert typeof(d) == "bytes object", typeof(d)
171

172

173
def arithmetic():
174
    """
175
    >>> arithmetic()
176
    """
177
    a = 1 + 2
178
    assert typeof(a) == "long", typeof(a)
179
    b = 1 + 1.5
180
    assert typeof(b) == "double", typeof(b)
181
    c = 1 + <object>2
182
    assert typeof(c) == "Python object", typeof(c)
183
    d = 1 * 1.5 ** 2
184
    assert typeof(d) == "double", typeof(d)
185
    e = 4 / 2
186
    assert typeof(e) == ("double" if IS_LANGUAGE_LEVEL_3 else "long"), typeof(e)
187
    f = 4 // 2
188
    assert typeof(f) == "long", typeof(f)
189
    g = 4 // <int>2
190
    assert typeof(g) == "long", typeof(g)
191
    h = int(2) / 3.0
192
    assert typeof(h) == "double", typeof(h)
193
    i = 3.0 + int(5)
194
    assert typeof(h) == "double", typeof(h)
195
    j = int(-1) + 1.0
196
    assert typeof(j) == "double", typeof(j)
197
    k = 7.0 - int(2)
198
    assert typeof(k) == "double", typeof(k)
199

200
cdef class some_class:
201
    pass
202

203
def unary_operators():
204
    """
205
    >>> unary_operators()
206
    """
207
    cdef int x = 1
208
    assert typeof(~x) == "int", typeof(~x)
209
    cdef some_class obj
210
    assert typeof(~obj) == "Python object", typeof(~obj)
211
    a = int(1)
212
    assert typeof(a) == "int object", typeof(a)
213
    b = not int(3)
214
    assert typeof(b) == "bint", typeof(b)
215
    c = +int(3)
216
    assert typeof(c) == "int object", typeof(c)
217
    d = -int(5)
218
    assert typeof(d) == "int object", typeof(d)
219
    e = ~int(5)
220
    assert typeof(e) == "int object", typeof(e)
221

222

223
def builtin_type_operations():
224
    """
225
    >>> builtin_type_operations()
226
    """
227
    b1 = b'a' * 10
228
    b1 = 10 * b'a'
229
    b1 = 10 * b'a' * 10
230
    assert typeof(b1) == "bytes object", typeof(b1)
231
    b2 = b'a' + b'b'
232
    assert typeof(b2) == "bytes object", typeof(b2)
233

234
    u1 = u'a' * 10
235
    u1 = 10 * u'a'
236
    assert typeof(u1) == "str object", typeof(u1)
237
    u2 = u'a' + u'b'
238
    assert typeof(u2) == "str object", typeof(u2)
239
    u3 = u'a%s' % u'b'
240
    u3 = u'a%s' % 10
241
    assert typeof(u3) == "str object", typeof(u3)
242

243
    s1 = "abc %s" % "x"
244
    s1 = "abc %s" % 10
245
    assert typeof(s1) == "str object", (typeof(s1), "str object")
246
    s2 = "abc %s" + "x"
247
    assert typeof(s2) == "str object", (typeof(s2), "str object")
248
    s3 = "abc %s" * 10
249
    s3 = "abc %s" * 10 * 10
250
    s3 = 10 * "abc %s" * 10
251
    assert typeof(s3) == "str object", (typeof(s3), "str object")
252

253
    x: int = 15
254
    f1 = x / 3
255
    assert typeof(f1) == ("double" if IS_LANGUAGE_LEVEL_3 else "Python object"), typeof(f1)
256
    i1 = x // 3
257
    assert typeof(i1) == "int object", typeof(i1)
258
    i2 = x * 3
259
    assert typeof(i2) == "int object", typeof(i2)
260

261
    L1 = [] + []
262
    assert typeof(L1) == "list object", typeof(L1)
263
    L2 = [] * 2
264
    assert typeof(L2) == "list object", typeof(L2)
265
    T1 = () + ()
266
    assert typeof(T1) == "tuple object", typeof(T1)
267
    T2 = () * 2
268
    assert typeof(T2) == "tuple object", typeof(T2)
269

270

271
def builtin_type_methods():
272
    """
273
    >>> builtin_type_methods()
274
    """
275
    l = []
276
    assert typeof(l) == 'list object', typeof(l)
277
    append = l.append
278
    assert typeof(append) == 'Python object', typeof(append)
279
    append(1)
280
    assert l == [1], str(l)
281

282
    u = u'abc def'
283
    split = u.split()
284
    assert typeof(split) == 'list object', typeof(split)
285

286
    str_result1 = u.upper()
287
    assert typeof(str_result1) == "str object", typeof(str_result1)
288
    str_result2 = u.upper().lower()
289
    assert typeof(str_result2) == "str object", typeof(str_result2)
290
    str_result3 = u.upper().lower().strip()
291
    assert typeof(str_result3) == "str object", typeof(str_result3)
292
    str_result4 = u.upper().lower().strip().lstrip()
293
    assert typeof(str_result4) == "str object", typeof(str_result4)
294
    str_result5 = u.upper().lower().strip().lstrip().rstrip()
295
    assert typeof(str_result5) == "str object", typeof(str_result5)
296
    str_result6 = u.upper().lower().strip().lstrip().rstrip().center(20)
297
    assert typeof(str_result6) == "str object", typeof(str_result6)
298
    str_result7 = u.upper().lower().strip().lstrip().rstrip().center(20).format()
299
    assert typeof(str_result7) == "str object", typeof(str_result7)
300
    str_result8 = u.upper().lower().strip().lstrip().rstrip().center(20).format().expandtabs(4)
301
    assert typeof(str_result8) == "str object", typeof(str_result8)
302
    str_result9 = u.upper().lower().strip().lstrip().rstrip().center(20).format().expandtabs(4).swapcase()
303
    assert typeof(str_result9) == "str object", typeof(str_result9)
304

305
    predicate1 = u.isupper()
306
    assert typeof(predicate1) == 'bint', typeof(predicate1)
307
    predicate2 = u.istitle()
308
    assert typeof(predicate2) == 'bint', typeof(predicate2)
309

310

311
cdef int cfunc(int x):
312
    return x+1
313

314
def c_functions():
315
    """
316
    >>> c_functions()
317
    """
318
    f = cfunc
319
    assert typeof(f) == 'int (*)(int) except? -1', typeof(f)
320
    assert 2 == f(1)
321

322
def builtin_functions():
323
    """
324
    >>> _abs, _getattr = builtin_functions()
325
    Python object
326
    Python object
327
    >>> _abs(-1)
328
    1
329
    >>> class o(object): pass
330
    >>> o.x = 1
331
    >>> _getattr(o, 'x')
332
    1
333
    """
334
    _abs = abs
335
    print(typeof(_abs))
336
    _getattr = getattr
337
    print(typeof(_getattr))
338
    return _abs, _getattr
339

340
def cascade():
341
    """
342
    >>> cascade()
343
    """
344
    a = 1.0
345
    b = a + 2
346
    c = b + 3
347
    d = c + 4
348
    assert typeof(d) == "double"
349
    e = a + b + c + d
350
    assert typeof(e) == "double"
351

352
def cascaded_assignment():
353
    """
354
    >>> cascaded_assignment()
355
    """
356
    a = b = c = d = 1.0
357
    assert typeof(a) == "double"
358
    assert typeof(b) == "double"
359
    assert typeof(c) == "double"
360
    assert typeof(d) == "double"
361
    e = a + b + c + d
362
    assert typeof(e) == "double"
363

364

365
def unpacking(x):
366
    """
367
    >>> unpacking(0)
368
    """
369
    a, b, c, (d, e) = x, 1, 2.0, [3, [5, 6]]
370
    assert typeof(a) == "Python object", typeof(a)
371
    assert typeof(b) == "long", typeof(b)
372
    assert typeof(c) == "double", typeof(c)
373
    assert typeof(d) == "long", typeof(d)
374
    assert typeof(e) == "list object", typeof(e)
375

376

377
def star_unpacking(*x):
378
    """
379
    >>> star_unpacking(1, 2)
380
    """
381
    a, b = x
382
    c, *d = x
383
    *e, f = x
384
    *g, g = x  # re-assignment
385
    assert typeof(a) == "Python object", typeof(a)
386
    assert typeof(b) == "Python object", typeof(b)
387
    assert typeof(c) == "Python object", typeof(c)
388
    assert typeof(d) == "list object", typeof(d)
389
    assert typeof(e) == "list object", typeof(e)
390
    assert typeof(f) == "Python object", typeof(f)
391
    assert typeof(g) == "Python object", typeof(f)
392

393

394
def increment():
395
    """
396
    >>> increment()
397
    """
398
    a = 5
399
    a += 1
400
    assert typeof(a) == "long"
401

402
def loop():
403
    """
404
    >>> loop()
405
    """
406
    for a in range(10):
407
        pass
408
    assert typeof(a) == "long"
409

410
    b = 1.0
411
    for b in range(5):
412
        pass
413
    assert typeof(b) == "double"
414

415
    for c from 0 <= c < 10 by .5:
416
        pass
417
    assert typeof(c) == "double"
418

419
    for d in range(0, 10L, 2):
420
        pass
421
    assert typeof(a) == "long"
422

423
def loop_over_charptr():
424
    """
425
    >>> print( loop_over_charptr() )
426
    char
427
    """
428
    cdef char* char_ptr_string = 'abcdefg'
429
    for c in char_ptr_string:
430
        pass
431
    return typeof(c)
432

433
def loop_over_bytes_literal():
434
    """
435
    >>> print( loop_over_bytes_literal() )
436
    Python object
437
    """
438
    for c in b'abcdefg':
439
        pass
440
    return typeof(c)
441

442
def loop_over_bytes():
443
    """
444
    >>> print( loop_over_bytes() )
445
    Python object
446
    """
447
    cdef bytes bytes_string = b'abcdefg'
448
    # bytes in Py2, int in Py3
449
    for c in bytes_string:
450
        pass
451
    return typeof(c)
452

453
def loop_over_str():
454
    """
455
    >>> loop_over_str()
456
    """
457
    cdef str string = 'abcdefg'
458
    # str (bytes) in Py2, str (unicode) in Py3
459
    for c in string:
460
        pass
461
    assert typeof(c) == 'Py_UCS4', typeof(c)
462

463
def loop_over_unicode():
464
    """
465
    >>> print( loop_over_unicode() )
466
    Py_UCS4
467
    """
468
    cdef unicode ustring = u'abcdefg'
469
    # Py_UCS4 can represent any Unicode character
470
    for uchar in ustring:
471
        pass
472
    return typeof(uchar)
473

474
def loop_over_unicode_literal():
475
    """
476
    >>> print( loop_over_unicode_literal() )
477
    Py_UCS4
478
    """
479
    # Py_UCS4 can represent any Unicode character
480
    for uchar in u'abcdefg':
481
        pass
482
    return typeof(uchar)
483

484
def loop_over_int_array():
485
    """
486
    >>> print( loop_over_int_array() )
487
    int
488
    """
489
    cdef int[10] int_array
490
    for i in int_array:
491
        pass
492
    return typeof(i)
493

494
cdef struct MyStruct:
495
    int a
496

497
def loop_over_struct_ptr():
498
    """
499
    >>> print( loop_over_struct_ptr() )
500
    MyStruct
501
    """
502
    cdef MyStruct[10] a_list
503
    cdef MyStruct *a_ptr = a_list
504
    for i in a_list[:10]:
505
        pass
506
    return typeof(i)
507

508
cdef unicode retu():
509
    return u"12345"
510

511
cdef bytes retb():
512
    return b"12345"
513

514
def conditional(x):
515
    """
516
    >>> conditional(True)
517
    (True, 'Python object')
518
    >>> conditional(False)
519
    (False, 'Python object')
520
    """
521
    if x:
522
        a = retu()
523
    else:
524
        a = retb()
525
    return type(a) is unicode, typeof(a)
526

527
##################################################
528
# type inference tests that work in 'safe' mode
529

530
@infer_types(None)
531
def double_inference():
532
    """
533
    >>> values, types = double_inference()
534
    >>> values == (1.0, 1.0*2, 1.0*2.0+2.0*2.0, 1.0*2.0)
535
    True
536
    >>> types
537
    ('double', 'double', 'double', 'Python object')
538
    """
539
    d_a = 1.0
540
    d_b = d_a * float(2)
541
    d_c = d_a * float(some_float_value()) + d_b * float(some_float_value())
542
    o_d = d_a * some_float_value()
543
    return (d_a,d_b,d_c,o_d), (typeof(d_a), typeof(d_b), typeof(d_c), typeof(o_d))
544

545
cdef object some_float_value():
546
    return 2.0
547

548

549
@infer_types(None)
550
@cython.test_fail_if_path_exists('//DefNode//NameNode[@type.is_pyobject = True]')
551
@cython.test_assert_path_exists('//DefNode//NameNode[@type.is_pyobject]',
552
                                '//DefNode//NameNode[@type.is_pyobject = False]')
553
def double_loop():
554
    """
555
    >>> double_loop() == 1.0 * 10
556
    True
557
    """
558
    cdef int i
559
    d = 1.0
560
    for i in range(9):
561
        d += 1.0
562
    return d
563

564
@infer_types(None)
565
def safe_only():
566
    """
567
    >>> safe_only()
568
    """
569
    a = 1.0
570
    assert typeof(a) == "double", typeof(a)
571
    b = 1
572
    assert typeof(b) == "long", typeof(b)
573
    c = MyType()
574
    assert typeof(c) == "MyType", typeof(c)
575
    for i in range(10): pass
576
    assert typeof(i) == "long", typeof(i)
577
    d = 1
578
    res = ~d
579
    assert typeof(d) == "long", typeof(d)
580

581
    pyint_val: int = 5
582
    div_res = pyint_val / 7
583
    assert typeof(div_res) == ("double" if IS_LANGUAGE_LEVEL_3 else "Python object"), typeof(div_res)
584

585
    s = "abc"
586
    assert typeof(s) == "str object", (typeof(s), "str object")
587
    cdef str t = "def"
588
    assert typeof(t) == "str object", (typeof(t), "str object")
589

590
    # potentially overflowing arithmetic
591
    e = 1
592
    e += 1
593
    assert typeof(e) == "Python object", typeof(e)
594
    f = 1
595
    res = f * 10
596
    assert typeof(f) == "Python object", typeof(f)
597
    g = 1
598
    res = 10*(~g)
599
    assert typeof(g) == "Python object", typeof(g)
600
    for j in range(10):
601
        res = -j
602
    assert typeof(j) == "Python object", typeof(j)
603
    h = 1
604
    res = abs(h)
605
    assert typeof(h) == "Python object", typeof(h)
606
    cdef int c_int = 1
607
    assert typeof(abs(c_int)) == "int", typeof(abs(c_int))
608

609
    # float can be inferred
610
    cdef float fl = 5.0
611
    from_fl = fl
612
    assert typeof(from_fl) == "float", typeof(from_fl)
613

614

615
@infer_types(None)
616
def safe_c_functions():
617
    """
618
    >>> safe_c_functions()
619
    """
620
    f = cfunc
621
    assert typeof(f) == 'int (*)(int) except? -1', typeof(f)
622
    assert 2 == f(1)
623

624
@infer_types(None)
625
def ptr_types():
626
    """
627
    >>> ptr_types()
628
    """
629
    cdef int a
630
    a_ptr = &a
631
    assert typeof(a_ptr) == "int *", typeof(a_ptr)
632
    a_ptr_ptr = &a_ptr
633
    assert typeof(a_ptr_ptr) == "int **", typeof(a_ptr_ptr)
634
    cdef int[1] b
635
    b_ref = b
636
    assert typeof(b_ref) == "int *", typeof(b_ref)
637
    ptr = &a
638
    ptr = b
639
    assert typeof(ptr) == "int *", typeof(ptr)
640

641
def const_types(const double x, double y, double& z):
642
    """
643
    >>> const_types(1, 1, 1)
644
    """
645
    a = x
646
    a = y
647
    a = z
648
    assert typeof(a) == "double", typeof(a)
649

650
@infer_types(None)
651
def args_tuple_keywords(*args, **kwargs):
652
    """
653
    >>> args_tuple_keywords(1,2,3, a=1, b=2)
654
    """
655
    assert typeof(args) == "tuple object", typeof(args)
656
    assert typeof(kwargs) == "dict object", typeof(kwargs)
657

658
@infer_types(None)
659
def args_tuple_keywords_reassign_same(*args, **kwargs):
660
    """
661
    >>> args_tuple_keywords_reassign_same(1,2,3, a=1, b=2)
662
    """
663
    assert typeof(args) == "tuple object", typeof(args)
664
    assert typeof(kwargs) == "dict object", typeof(kwargs)
665

666
    args = ()
667
    kwargs = {}
668

669
@infer_types(None)
670
def args_tuple_keywords_reassign_pyobjects(*args, **kwargs):
671
    """
672
    >>> args_tuple_keywords_reassign_pyobjects(1,2,3, a=1, b=2)
673
    """
674
    assert typeof(args) == "Python object", typeof(args)
675
    assert typeof(kwargs) == "Python object", typeof(kwargs)
676

677
    args = []
678
    kwargs = "test"
679

680
#                 / A -> AA -> AAA
681
# Base0 -> Base -
682
#                 \ B -> BB
683
# C -> CC
684

685
cdef class Base0: pass
686
cdef class Base(Base0): pass
687
cdef class A(Base): pass
688
cdef class AA(A): pass
689
cdef class AAA(AA): pass
690
cdef class B(Base): pass
691
cdef class BB(B): pass
692
cdef class C: pass
693
cdef class CC(C): pass
694

695
@infer_types(None)
696
def common_extension_type_base():
697
    """
698
    >>> common_extension_type_base()
699
    """
700
    x = A()
701
    x = AA()
702
    assert typeof(x) == "A", typeof(x)
703
    y = A()
704
    y = B()
705
    assert typeof(y) == "Base", typeof(y)
706
    z = AAA()
707
    z = BB()
708
    assert typeof(z) == "Base", typeof(z)
709
    w = A()
710
    w = CC()
711
    assert typeof(w) == "Python object", typeof(w)
712

713
cdef class AcceptsKeywords:
714
    def __init__(self, *args, **kwds):
715
        pass
716

717
@infer_types(None)
718
def constructor_call():
719
    """
720
    >>> constructor_call()
721
    """
722
    x = AcceptsKeywords(a=1, b=2)
723
    assert typeof(x) == "AcceptsKeywords", typeof(x)
724

725

726
@infer_types(None)
727
def large_literals():
728
    """
729
    >>> large_literals()
730
    """
731
    # It's only safe to infer small integer literals.
732
    a = 10
733
    b = 100000000000000000000000000000000
734
    assert typeof(a) == "long", typeof(a)
735
    assert typeof(b) == "Python object", typeof(b)
736
    c, d = 10, 100000000000000000000000000000000
737
    assert typeof(c) == "long", typeof(c)
738
    assert typeof(d) == "Python object", typeof(d)
739

740

741
class EmptyContextManager(object):
742
    def __enter__(self):
743
        return None
744
    def __exit__(self, *args):
745
        return 0
746

747
def with_statement():
748
    """
749
    >>> with_statement()
750
    Python object
751
    Python object
752
    """
753
    x = 1.0
754
    with EmptyContextManager() as x:
755
        print(typeof(x))
756
    print(typeof(x))
757
    return x
758

759
@cython.final
760
cdef class TypedContextManager(object):
761
    cpdef double __enter__(self):
762
        return 2.0
763
    def __exit__(self, *args):
764
        return 0
765

766
def with_statement_typed():
767
    """
768
    >>> with_statement_typed()
769
    double
770
    double
771
    2.0
772
    """
773
    x = 1.0
774
    with TypedContextManager() as x:
775
        print(typeof(x))
776
    print(typeof(x))
777
    return x
778

779
def with_statement_untyped():
780
    """
781
    >>> with_statement_untyped()
782
    Python object
783
    Python object
784
    2.0
785
    """
786
    x = 1.0
787
    cdef object t = TypedContextManager()
788
    with t as x:
789
        print(typeof(x))
790
    print(typeof(x))
791
    return x
792

793
def self_lookup(a):
794
    b = a
795
    b = b.foo(keyword=None)
796
    print(typeof(b))
797

798
# Regression test for trac #638.
799

800
def bar(foo):
801
    qux = foo
802
    quux = foo[qux.baz]
803

804

805
cdef enum MyEnum:
806
    enum_x = 1
807
    enum_y = 2
808

809
ctypedef long my_long
810
def test_int_typedef_inference():
811
    """
812
    >>> test_int_typedef_inference()
813
    """
814
    cdef long x = 1
815
    cdef my_long y = 2
816
    cdef long long z = 3
817
    assert typeof(x + y) == typeof(y + x) == 'my_long', typeof(x + y)
818
    assert typeof(y + z) == typeof(z + y) == 'long long', typeof(y + z)
819

820
from libc.stdint cimport int32_t, int64_t
821
def int64_long_sum():
822
    cdef long x = 1
823
    cdef int32_t x32 = 2
824
    cdef int64_t x64 = 3
825
    cdef unsigned long ux = 4
826
    assert typeof(x + x32) == typeof(x32 + x) == 'long', typeof(x + x32)
827
    assert typeof(x + x64) == typeof(x64 + x) == 'int64_t', typeof(x + x64)
828
    # The correct answer here is either unsigned long or int64_t, depending on
829
    # whether sizeof(long) == 64 or not.  Incorrect signedness is probably
830
    # preferable to incorrect width.
831
    assert typeof(ux + x64) == typeof(x64 + ux) == 'int64_t', typeof(ux + x64)
832

833
cdef class InferInProperties:
834
    """
835
    >>> InferInProperties().x
836
    ('double', 'str object', 'MyEnum', 'MyEnum')
837
    """
838
    cdef MyEnum attr
839
    def __cinit__(self):
840
        self.attr = enum_x
841

842
    property x:
843
        def __get__(self):
844
            a = 1.0
845
            b = u'abc'
846
            c = self.attr
847
            d = enum_y
848
            c = d
849
            return typeof(a), typeof(b), typeof(c), typeof(d)
850

851
cdef class WithMethods:
852
    cdef int offset
853
    def __init__(self, offset):
854
        self.offset = offset
855
    cpdef int one_arg(self, int x):
856
        return x + self.offset
857
    cpdef int default_arg(self, int x, int y=0):
858
        return x + y + self.offset
859

860
def test_bound_methods():
861
  """
862
  >>> test_bound_methods()
863
  """
864
  o = WithMethods(10)
865
  assert typeof(o) == 'WithMethods', typeof(o)
866

867
  one_arg = o.one_arg
868
  assert one_arg(2) == 12, one_arg(2)
869

870
  default_arg = o.default_arg
871
  assert default_arg(2) == 12, default_arg(2)
872
  assert default_arg(2, 3) == 15, default_arg(2, 2)
873

874
def test_builtin_max():
875
    """
876
    # builtin max is slightly complicated because it gets transformed to EvalWithTempExprNode
877
    # See https://github.com/cython/cython/issues/4155
878
    >>> test_builtin_max()
879
    """
880
    class C:
881
        a = 2
882
        def get_max(self):
883
            a = max(self.a, self.a)
884
            assert typeof(a) == "Python object", typeof(a)
885
    C().get_max()
886

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

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

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

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