Debian Codegraph @

mypyc/test-data/run-tuples.test

raw
1 # Test cases for tuples (compile and run)
2
3 [case testTuple]
4 from typing import List, Optional, Tuple
5 from typing import Tuple
6 def f(x: Tuple[int, int]) -> Tuple[int,int]:
7 return x
8
9 def lurr(x: List[Optional[Tuple[int, str]]]) -> object:
10 return x[0]
11
12 def asdf(x: Tuple[int, str]) -> None:
13 pass
14 [file driver.py]
15 from testutil import assertRaises
16 from native import f, lurr, asdf
17
18 assert f((1,2)) == (1, 2)
19 assert lurr([(1, '2')]) == (1, '2')
20
21 with assertRaises(TypeError):
22 print(lurr([(1, 2)]))
23
24 with assertRaises(TypeError):
25 asdf((1, 2))
26
27 [case testTupleGet]
28 from typing import Tuple
29 def f(x: Tuple[Tuple[int, bool], int]) -> int:
30 return x[0][0]
31 [file driver.py]
32 from native import f
33 print(f(((1,True),2)))
34 big_number = pow(2, 80)
35 print(f(((big_number,True),2)))
36 [out]
37 1
38 1208925819614629174706176
39
40 [case testSequenceTupleArg]
41 from typing import Tuple
42 def f(x: Tuple[int, ...]) -> int:
43 return x[1]
44 [file driver.py]
45 from native import f
46 print(f((1,2,3,4)))
47 [out]
48 2
49
50 [case testTupleAttr]
51 from typing import Tuple
52 class C:
53 b: Tuple[Tuple[Tuple[int, int], int], int, str, object]
54 c: Tuple[()]
55 def f() -> None:
56 c = C()
57 c.b = (((1, 2), 2), 1, 'hi', 'hi2')
58 print(c.b)
59
60 def g() -> None:
61 try:
62 h()
63 except Exception:
64 print('caught the exception')
65
66 def h() -> Tuple[Tuple[Tuple[int, int], int], int, str, object]:
67 raise Exception('Intentional exception')
68 [file driver.py]
69 from native import f, g, C
70 f()
71 g()
72 assert not hasattr(C(), 'c')
73 [out]
74 (((1, 2), 2), 1, 'hi', 'hi2')
75 caught the exception
76
77 [case testNamedTupleAttributeRun]
78 from typing import NamedTuple
79
80 NT = NamedTuple('NT', [('x', int), ('y', int)])
81
82 def f(nt: NT) -> int:
83 if nt.x > nt.y:
84 return nt.x
85 return nt.y
86
87 nt = NT(1, 2)
88 [file driver.py]
89 from native import NT, nt, f
90
91 assert f(nt) == 2
92 assert f(NT(3, 2)) == 3
93
94 class Sub(NT):
95 pass
96 assert f(Sub(3, 2)) == 3
97
98 -- Ref: https://github.com/mypyc/mypyc/issues/924
99 [case testNamedTupleClassSyntax]
100 from typing import Dict, List, NamedTuple, Optional, Tuple, Union, final
101
102 class FuncIR: pass
103
104 StealsDescription = Union[bool, List[bool]]
105
106 class Record(NamedTuple):
107 st_mtime: float
108 st_size: int
109 is_borrowed: bool
110 hash: str
111 python_path: Tuple[str, ...]
112 type: 'ClassIR'
113 method: FuncIR
114 shadow_method: Optional[FuncIR]
115 classes: Dict[str, 'ClassIR']
116 steals: StealsDescription
117 ordering: Optional[List[int]]
118 extra_int_constants: List[Tuple[int]]
119
120 # Make sure mypyc loads the annotation string for this forward reference.
121 # Ref: https://github.com/mypyc/mypyc/issues/938
122 class ClassIR: pass
123
124 # Ref: https://github.com/mypyc/mypyc/issues/927
125 @final
126 class Inextensible(NamedTuple):
127 x: int
128
129 [file driver.py]
130 import sys
131 from typing import Optional
132 from native import ClassIR, FuncIR, Record
133
134 HAVE_TEST = False
135 if sys.version_info >= (3, 14):
136 try:
137 from test.support import EqualToForwardRef
138 type_forward_ref = EqualToForwardRef
139 HAVE_TEST = True
140 except ImportError as e:
141 # catch the case of a pymanager installed Python
142 # without the test module. It is excluded by default
143 # on Windows.
144 msg = 'Missing "test" module.'
145 if sys.platform == "win32":
146 msg += (' Please install a version of Python with the test module.'
147 ' If you are using pymanager, try running pymanager install --force PythonTest\\<version>')
148 raise ImportError(msg) from e
149
150 if not HAVE_TEST:
151 from typing import ForwardRef
152 type_forward_ref = ForwardRef
153
154 assert Record.__annotations__ == {
155 'st_mtime': float,
156 'st_size': int,
157 'is_borrowed': bool,
158 'hash': str,
159 'python_path': tuple,
160 'type': type_forward_ref('ClassIR'),
161 'method': FuncIR,
162 'shadow_method': type,
163 'classes': dict,
164 'steals': type,
165 'ordering': type,
166 'extra_int_constants': list,
167 }, Record.__annotations__
168
169 [case testTupleOps]
170 from typing import Tuple, Final, List, Any, Optional, cast
171 from testutil import assertRaises
172
173 def f() -> Tuple[()]:
174 return ()
175
176 def test_empty_tuple() -> None:
177 assert f() == ()
178
179 def f2() -> Any:
180 return ()
181
182 def test_empty_tuple_with_any_type():
183 assert f2() == ()
184
185 def f3() -> int:
186 x = (False, 1)
187 return x[1]
188
189 def test_new_tuple() -> None:
190 assert f3() == 1
191
192 def f4(y: int) -> int:
193 x = (False, y)
194 return x[1]
195
196 def test_new_tuple_boxed_int() -> None:
197 big_number = 1208925819614629174706176
198 assert f4(big_number) == big_number
199
200 def f5(x: List[int]) -> int:
201 return tuple(x)[1]
202
203 def test_sequence_tuple() -> None:
204 assert f5([1,2,3,4]) == 2
205
206 def f6(x: List[int]) -> int:
207 return len(tuple(x))
208
209 def test_sequence_tuple_len() -> None:
210 assert f6([1,2,3,4]) == 4
211
212 def f7(x: List[Tuple[int, int]]) -> int:
213 a, b = x[0]
214 return a + b
215
216 def test_unbox_tuple() -> None:
217 assert f7([(5, 6)]) == 11
218
219 def test_comparison() -> None:
220 assert ('x','y') == ('x','y')
221 assert not(('x','y') != ('x','y'))
222
223 assert ('x','y') != ('x','y',1)
224 assert not(('x','y') == ('x','y',1))
225
226 assert ('x','y',1) != ('x','y')
227 assert not(('x','y',1) == ('x','y'))
228
229 assert ('x','y') != ()
230 assert not(('x','y') == ())
231
232 assert () != ('x','y')
233 assert not(() == ('x','y'))
234
235 # Test that order is irrelevant to unions. Really I only care that this builds.
236
237 class A:
238 pass
239
240 def lol() -> A:
241 return A()
242
243 def foo(x: bool, y: bool) -> Tuple[Optional[A], bool]:
244 z = lol()
245
246 return None if y else z, x
247
248 def test_slicing() -> None:
249 # Use dummy adds to avoid constant folding
250 zero = int()
251 two = zero + 2
252 s: Tuple[str, ...] = ("f", "o", "o", "b", "a", "r")
253 assert s[two:] == ("o", "b", "a", "r")
254 assert s[:two] == ("f", "o")
255 assert s[two:-two] == ("o", "b")
256 assert s[two:two] == ()
257 assert s[two:two + 1] == ("o",)
258 assert s[-two:] == ("a", "r")
259 assert s[:-two] == ("f", "o", "o", "b")
260 assert s[:] == ("f", "o", "o", "b", "a", "r")
261 assert s[two:333] == ("o", "b", "a", "r")
262 assert s[333:two] == ()
263 assert s[two:-333] == ()
264 assert s[-333:two] == ("f", "o")
265 long_int: int = 1000 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000
266 assert s[1:long_int] == ("o", "o", "b", "a", "r")
267 assert s[long_int:] == ()
268 assert s[-long_int:-1] == ("f", "o", "o", "b", "a")
269
270 def f8(val: int) -> bool:
271 return val % 2 == 0
272
273 abc: Final = "abc"
274
275 def known_length() -> tuple[str, ...]:
276 return tuple(str(x) for x in [*abc, *"def", *b"ghi", ("j", "k"), *("l", "m", "n")])
277
278 def test_sequence_generator() -> None:
279 source_list = [1, 2, 3]
280 a = tuple(f8(x) for x in source_list)
281 assert a == (False, True, False)
282
283 source_tuple: Tuple[int, ...] = (1, 2, 3)
284 a = tuple(f8(x) for x in source_tuple)
285 assert a == (False, True, False)
286
287 source_fixed_length_tuple = (1, 2, 3, 4)
288 a = tuple(f8(x) for x in source_fixed_length_tuple)
289 assert a == (False, True, False, True)
290
291 source_str = 'abbc'
292 b = tuple('s:' + x for x in source_str)
293 assert b == ('s:a', 's:b', 's:b', 's:c')
294
295 assert known_length() == ('a', 'b', 'c', 'd', 'e', 'f', '103', '104', '105', "('j', 'k')", 'l', 'm', 'n')
296
297 TUPLE: Final[Tuple[str, ...]] = ('x', 'y')
298
299 def test_final_boxed_tuple() -> None:
300 t = TUPLE
301 assert t == ('x', 'y')
302 assert 'x' in TUPLE
303 assert 'y' in TUPLE
304 b: object = 'z' in TUPLE
305 assert not b
306 assert 'z' not in TUPLE
307 b2: object = 'x' not in TUPLE
308 assert not b2
309 b3: object = 'y' not in TUPLE
310 assert not b3
311
312 TUP2: Final = ('x', 'y')
313 TUP1: Final = ('x',)
314 TUP0: Final = ()
315
316 def test_final_tuple_in() -> None:
317 assert 'x' + str() in TUP2
318 assert 'y' + str() in TUP2
319 b: object = 'z' + str() in TUP2
320 assert not b
321
322 assert 'x' + str() in TUP1
323 b2: object = 'y' in TUP1
324 assert not b2
325
326 b3: object = 'x' in TUP0
327 assert not b3
328
329 def test_final_tuple_not_in() -> None:
330 assert 'z' + str() not in TUP2
331 b: object = 'x' + str() not in TUP2
332 assert not b
333 b2: object = 'y' + str() not in TUP2
334 assert not b2
335
336 assert 'y' + str() not in TUP1
337 b3: object = 'x' not in TUP1
338 assert not b2
339
340 assert 'x' not in TUP0
341
342 log: list[str] = []
343
344 def f_a() -> str:
345 log.append('f_a')
346 return 'a'
347
348 def f_a2() -> str:
349 log.append('f_a2')
350 return 'a'
351
352 def f_b() -> str:
353 log.append('f_b')
354 return 'b'
355
356 def f_c() -> str:
357 log.append('f_c')
358 return 'c'
359
360 def test_tuple_in_order_of_evaluation() -> None:
361 log.clear()
362 assert f_a() in (f_b(), f_a2())
363 assert log ==["f_a", "f_b", "f_a2"]
364
365 log.clear()
366 assert f_a() not in (f_b(), f_c())
367 assert log ==["f_a", "f_b", "f_c"]
368
369 log.clear()
370 assert f_a() in (f_b(), f_a2(), f_c())
371 assert log ==["f_a", "f_b", "f_a2", "f_c"]
372
373 def f_t() -> tuple[str, ...]:
374 log.append('f_t')
375 return ('x', 'a')
376
377 def test_tuple_in_non_specialized() -> None:
378 log.clear()
379 assert f_a() in f_t()
380 assert log == ["f_a", "f_t"]
381
382 log.clear()
383 assert f_b() not in f_t()
384 assert log == ["f_b", "f_t"]
385
386 def test_add() -> None:
387 res = (1, 2, 3, 4)
388 assert (1, 2) + (3, 4) == res
389 with assertRaises(TypeError, 'can only concatenate tuple (not "list") to tuple'):
390 assert (1, 2) + cast(Any, [3, 4]) == res
391
392 def multiply(a: Tuple[Any, ...], b: int) -> Tuple[Any, ...]:
393 return a * b
394
395 def test_multiply() -> None:
396 res = (1, 1, 1)
397 assert (1,) * 3 == res
398 assert 3 * (1,) == res
399 assert multiply((1,), 3) == res
400
401 # Ref: https://github.com/mypyc/mypyc/issues/1179
402 def test_tuple_with_walrus() -> None:
403 i = 0
404 assert (i, (i := i + 1), i, (i := i + 1), i, (i := i + 1), i) == (0, 1, 1, 2, 2, 3, 3)
405
406 def test_nested_tuple_with_walrus() -> None:
407 i = 0
408 assert ((i, i), (i := i + 1)) == ((0, 0), 1)
409
410 [case testIsInstance]
411 from copysubclass import subc
412 def test_built_in() -> None:
413 assert isinstance((), tuple)
414 assert isinstance((1, 2), tuple)
415 assert isinstance(('a', 'b', 'c'), tuple)
416 assert isinstance(subc(()), tuple)
417 assert isinstance(subc((1, 2)), tuple)
418 assert isinstance(subc(('a', 'b', 'c')), tuple)
419
420 assert not isinstance(set(), tuple)
421 assert not isinstance({}, tuple)
422 assert not isinstance([1,2,3], tuple)
423 assert not isinstance({'a','b'}, tuple)
424 assert not isinstance(int() + 1, tuple)
425 assert not isinstance(str() + 'a', tuple)
426
427 def test_user_defined() -> None:
428 from userdefinedtuple import tuple
429
430 assert isinstance(tuple(), tuple)
431 assert not isinstance((1, tuple()), tuple)
432
433 [file copysubclass.py]
434 from typing import Any
435 class subc(tuple[Any, ...]):
436 pass
437
438 [file userdefinedtuple.py]
439 class tuple:
440 pass