Debian Codegraph @

Lib/test/test_syntax.py

raw
1 """This module tests SyntaxErrors.
2
3 Here's an example of the sort of thing that is tested.
4
5 >>> def f(x):
6 ... global x
7 Traceback (most recent call last):
8 SyntaxError: name 'x' is parameter and global
9
10 The tests are all raise SyntaxErrors. They were created by checking
11 each C call that raises SyntaxError. There are several modules that
12 raise these exceptions-- ast.c, compile.c, future.c, pythonrun.c, and
13 symtable.c.
14
15 The parser itself outlaws a lot of invalid syntax. None of these
16 errors are tested here at the moment. We should add some tests; since
17 there are infinitely many programs with invalid syntax, we would need
18 to be judicious in selecting some.
19
20 The compiler generates a synthetic module name for code executed by
21 doctest. Since all the code comes from the same module, a suffix like
22 [1] is appended to the module name, As a consequence, changing the
23 order of tests in this module means renumbering all the errors after
24 it. (Maybe we should enable the ellipsis option for these tests.)
25
26 In ast.c, syntax errors are raised by calling ast_error().
27
28 Errors from set_context():
29
30 >>> obj.None = 1
31 Traceback (most recent call last):
32 SyntaxError: invalid syntax
33
34 >>> None = 1
35 Traceback (most recent call last):
36 SyntaxError: cannot assign to None
37
38 >>> obj.True = 1
39 Traceback (most recent call last):
40 SyntaxError: invalid syntax
41
42 >>> True = 1
43 Traceback (most recent call last):
44 SyntaxError: cannot assign to True
45
46 >>> (True := 1)
47 Traceback (most recent call last):
48 SyntaxError: cannot use assignment expressions with True
49
50 >>> obj.__debug__ = 1
51 Traceback (most recent call last):
52 SyntaxError: cannot assign to __debug__
53
54 >>> __debug__ = 1
55 Traceback (most recent call last):
56 SyntaxError: cannot assign to __debug__
57
58 >>> (__debug__ := 1)
59 Traceback (most recent call last):
60 SyntaxError: cannot assign to __debug__
61
62 >>> del __debug__
63 Traceback (most recent call last):
64 SyntaxError: cannot delete __debug__
65
66 >>> f() = 1
67 Traceback (most recent call last):
68 SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
69
70 >>> yield = 1
71 Traceback (most recent call last):
72 SyntaxError: assignment to yield expression not possible
73
74 >>> del f()
75 Traceback (most recent call last):
76 SyntaxError: cannot delete function call
77
78 >>> a + 1 = 2
79 Traceback (most recent call last):
80 SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
81
82 >>> (x for x in x) = 1
83 Traceback (most recent call last):
84 SyntaxError: cannot assign to generator expression
85
86 >>> 1 = 1
87 Traceback (most recent call last):
88 SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
89
90 >>> "abc" = 1
91 Traceback (most recent call last):
92 SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
93
94 >>> b"" = 1
95 Traceback (most recent call last):
96 SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
97
98 >>> ... = 1
99 Traceback (most recent call last):
100 SyntaxError: cannot assign to ellipsis here. Maybe you meant '==' instead of '='?
101
102 >>> `1` = 1
103 Traceback (most recent call last):
104 SyntaxError: invalid syntax
105
106 If the left-hand side of an assignment is a list or tuple, an illegal
107 expression inside that contain should still cause a syntax error.
108 This test just checks a couple of cases rather than enumerating all of
109 them.
110
111 >>> (a, "b", c) = (1, 2, 3)
112 Traceback (most recent call last):
113 SyntaxError: cannot assign to literal
114
115 >>> (a, True, c) = (1, 2, 3)
116 Traceback (most recent call last):
117 SyntaxError: cannot assign to True
118
119 >>> (a, __debug__, c) = (1, 2, 3)
120 Traceback (most recent call last):
121 SyntaxError: cannot assign to __debug__
122
123 >>> (a, *True, c) = (1, 2, 3)
124 Traceback (most recent call last):
125 SyntaxError: cannot assign to True
126
127 >>> (a, *__debug__, c) = (1, 2, 3)
128 Traceback (most recent call last):
129 SyntaxError: cannot assign to __debug__
130
131 >>> [a, b, c + 1] = [1, 2, 3]
132 Traceback (most recent call last):
133 SyntaxError: cannot assign to expression
134
135 >>> [a, b[1], c + 1] = [1, 2, 3]
136 Traceback (most recent call last):
137 SyntaxError: cannot assign to expression
138
139 >>> [a, b.c.d, c + 1] = [1, 2, 3]
140 Traceback (most recent call last):
141 SyntaxError: cannot assign to expression
142
143 >>> a if 1 else b = 1
144 Traceback (most recent call last):
145 SyntaxError: cannot assign to conditional expression
146
147 >>> a = 42 if True
148 Traceback (most recent call last):
149 SyntaxError: expected 'else' after 'if' expression
150
151 >>> a = (42 if True)
152 Traceback (most recent call last):
153 SyntaxError: expected 'else' after 'if' expression
154
155 >>> a = [1, 42 if True, 4]
156 Traceback (most recent call last):
157 SyntaxError: expected 'else' after 'if' expression
158
159 >>> if True:
160 ... print("Hello"
161 ...
162 ... if 2:
163 ... print(123))
164 Traceback (most recent call last):
165 SyntaxError: invalid syntax
166
167 >>> True = True = 3
168 Traceback (most recent call last):
169 SyntaxError: cannot assign to True
170
171 >>> x = y = True = z = 3
172 Traceback (most recent call last):
173 SyntaxError: cannot assign to True
174
175 >>> x = y = yield = 1
176 Traceback (most recent call last):
177 SyntaxError: assignment to yield expression not possible
178
179 >>> a, b += 1, 2
180 Traceback (most recent call last):
181 SyntaxError: 'tuple' is an illegal expression for augmented assignment
182
183 >>> (a, b) += 1, 2
184 Traceback (most recent call last):
185 SyntaxError: 'tuple' is an illegal expression for augmented assignment
186
187 >>> [a, b] += 1, 2
188 Traceback (most recent call last):
189 SyntaxError: 'list' is an illegal expression for augmented assignment
190
191 Invalid targets in `for` loops and `with` statements should also
192 produce a specialized error message
193
194 >>> for a() in b: pass
195 Traceback (most recent call last):
196 SyntaxError: cannot assign to function call
197
198 >>> for (a, b()) in b: pass
199 Traceback (most recent call last):
200 SyntaxError: cannot assign to function call
201
202 >>> for [a, b()] in b: pass
203 Traceback (most recent call last):
204 SyntaxError: cannot assign to function call
205
206 >>> for (*a, b, c+1) in b: pass
207 Traceback (most recent call last):
208 SyntaxError: cannot assign to expression
209
210 >>> for (x, *(y, z.d())) in b: pass
211 Traceback (most recent call last):
212 SyntaxError: cannot assign to function call
213
214 >>> for a, b() in c: pass
215 Traceback (most recent call last):
216 SyntaxError: cannot assign to function call
217
218 >>> for a, b, (c + 1, d()): pass
219 Traceback (most recent call last):
220 SyntaxError: cannot assign to expression
221
222 >>> for i < (): pass
223 Traceback (most recent call last):
224 SyntaxError: invalid syntax
225
226 >>> for a, b
227 Traceback (most recent call last):
228 SyntaxError: invalid syntax
229
230 >>> with a as b(): pass
231 Traceback (most recent call last):
232 SyntaxError: cannot assign to function call
233
234 >>> with a as (b, c()): pass
235 Traceback (most recent call last):
236 SyntaxError: cannot assign to function call
237
238 >>> with a as [b, c()]: pass
239 Traceback (most recent call last):
240 SyntaxError: cannot assign to function call
241
242 >>> with a as (*b, c, d+1): pass
243 Traceback (most recent call last):
244 SyntaxError: cannot assign to expression
245
246 >>> with a as (x, *(y, z.d())): pass
247 Traceback (most recent call last):
248 SyntaxError: cannot assign to function call
249
250 >>> with a as b, c as d(): pass
251 Traceback (most recent call last):
252 SyntaxError: cannot assign to function call
253
254 >>> with a as b
255 Traceback (most recent call last):
256 SyntaxError: expected ':'
257
258 >>> p = p =
259 Traceback (most recent call last):
260 SyntaxError: invalid syntax
261
262 Comprehensions without 'in' keyword:
263
264 >>> [x for x if range(1)]
265 Traceback (most recent call last):
266 SyntaxError: 'in' expected after for-loop variables
267
268 >>> tuple(x for x if range(1))
269 Traceback (most recent call last):
270 SyntaxError: 'in' expected after for-loop variables
271
272 >>> [x for x() in a]
273 Traceback (most recent call last):
274 SyntaxError: cannot assign to function call
275
276 >>> [x for a, b, (c + 1, d()) in y]
277 Traceback (most recent call last):
278 SyntaxError: cannot assign to expression
279
280 >>> [x for a, b, (c + 1, d()) if y]
281 Traceback (most recent call last):
282 SyntaxError: 'in' expected after for-loop variables
283
284 >>> [x for x+1 in y]
285 Traceback (most recent call last):
286 SyntaxError: cannot assign to expression
287
288 >>> [x for x+1, x() in y]
289 Traceback (most recent call last):
290 SyntaxError: cannot assign to expression
291
292 Comprehensions creating tuples without parentheses
293 should produce a specialized error message:
294
295 >>> [x,y for x,y in range(100)]
296 Traceback (most recent call last):
297 SyntaxError: did you forget parentheses around the comprehension target?
298
299 >>> {x,y for x,y in range(100)}
300 Traceback (most recent call last):
301 SyntaxError: did you forget parentheses around the comprehension target?
302
303 # Missing commas in literals collections should not
304 # produce special error messages regarding missing
305 # parentheses, but about missing commas instead
306
307 >>> [1, 2 3]
308 Traceback (most recent call last):
309 SyntaxError: invalid syntax. Perhaps you forgot a comma?
310
311 >>> {1, 2 3}
312 Traceback (most recent call last):
313 SyntaxError: invalid syntax. Perhaps you forgot a comma?
314
315 >>> {1:2, 2:5 3:12}
316 Traceback (most recent call last):
317 SyntaxError: invalid syntax. Perhaps you forgot a comma?
318
319 >>> (1, 2 3)
320 Traceback (most recent call last):
321 SyntaxError: invalid syntax. Perhaps you forgot a comma?
322
323 # Make sure soft keywords constructs don't raise specialized
324 # errors regarding missing commas or other spezialiced errors
325
326 >>> match x:
327 ... y = 3
328 Traceback (most recent call last):
329 SyntaxError: invalid syntax
330
331 >>> match x:
332 ... case y:
333 ... 3 $ 3
334 Traceback (most recent call last):
335 SyntaxError: invalid syntax
336
337 >>> match x:
338 ... case $:
339 ... ...
340 Traceback (most recent call last):
341 SyntaxError: invalid syntax
342
343 >>> match ...:
344 ... case {**rest, "key": value}:
345 ... ...
346 Traceback (most recent call last):
347 SyntaxError: invalid syntax
348
349 >>> match ...:
350 ... case {**_}:
351 ... ...
352 Traceback (most recent call last):
353 SyntaxError: invalid syntax
354
355 # But prefixes of soft keywords should
356 # still raise specialized errors
357
358 >>> (mat x)
359 Traceback (most recent call last):
360 SyntaxError: invalid syntax. Perhaps you forgot a comma?
361
362 From compiler_complex_args():
363
364 >>> def f(None=1):
365 ... pass
366 Traceback (most recent call last):
367 SyntaxError: invalid syntax
368
369 From ast_for_arguments():
370
371 >>> def f(x, y=1, z):
372 ... pass
373 Traceback (most recent call last):
374 SyntaxError: parameter without a default follows parameter with a default
375
376 >>> def f(x, /, y=1, z):
377 ... pass
378 Traceback (most recent call last):
379 SyntaxError: parameter without a default follows parameter with a default
380
381 >>> def f(x, None):
382 ... pass
383 Traceback (most recent call last):
384 SyntaxError: invalid syntax
385
386 >>> def f(*None):
387 ... pass
388 Traceback (most recent call last):
389 SyntaxError: invalid syntax
390
391 >>> def f(**None):
392 ... pass
393 Traceback (most recent call last):
394 SyntaxError: invalid syntax
395
396 >>> def foo(/,a,b=,c):
397 ... pass
398 Traceback (most recent call last):
399 SyntaxError: at least one argument must precede /
400
401 >>> def foo(a,/,/,b,c):
402 ... pass
403 Traceback (most recent call last):
404 SyntaxError: / may appear only once
405
406 >>> def foo(a,/,a1,/,b,c):
407 ... pass
408 Traceback (most recent call last):
409 SyntaxError: / may appear only once
410
411 >>> def foo(a=1,/,/,*b,/,c):
412 ... pass
413 Traceback (most recent call last):
414 SyntaxError: / may appear only once
415
416 >>> def foo(a,/,a1=1,/,b,c):
417 ... pass
418 Traceback (most recent call last):
419 SyntaxError: / may appear only once
420
421 >>> def foo(a,*b,c,/,d,e):
422 ... pass
423 Traceback (most recent call last):
424 SyntaxError: / must be ahead of *
425
426 >>> def foo(a=1,*b,c=3,/,d,e):
427 ... pass
428 Traceback (most recent call last):
429 SyntaxError: / must be ahead of *
430
431 >>> def foo(a,*b=3,c):
432 ... pass
433 Traceback (most recent call last):
434 SyntaxError: var-positional argument cannot have default value
435
436 >>> def foo(a,*b: int=,c):
437 ... pass
438 Traceback (most recent call last):
439 SyntaxError: var-positional argument cannot have default value
440
441 >>> def foo(a,**b=3):
442 ... pass
443 Traceback (most recent call last):
444 SyntaxError: var-keyword argument cannot have default value
445
446 >>> def foo(a,**b: int=3):
447 ... pass
448 Traceback (most recent call last):
449 SyntaxError: var-keyword argument cannot have default value
450
451 >>> def foo(a,*a, b, **c, d):
452 ... pass
453 Traceback (most recent call last):
454 SyntaxError: arguments cannot follow var-keyword argument
455
456 >>> def foo(a,*a, b, **c, d=4):
457 ... pass
458 Traceback (most recent call last):
459 SyntaxError: arguments cannot follow var-keyword argument
460
461 >>> def foo(a,*a, b, **c, *d):
462 ... pass
463 Traceback (most recent call last):
464 SyntaxError: arguments cannot follow var-keyword argument
465
466 >>> def foo(a,*a, b, **c, **d):
467 ... pass
468 Traceback (most recent call last):
469 SyntaxError: arguments cannot follow var-keyword argument
470
471 >>> def foo(a=1,/,**b,/,c):
472 ... pass
473 Traceback (most recent call last):
474 SyntaxError: arguments cannot follow var-keyword argument
475
476 >>> def foo(*b,*d):
477 ... pass
478 Traceback (most recent call last):
479 SyntaxError: * argument may appear only once
480
481 >>> def foo(a,*b,c,*d,*e,c):
482 ... pass
483 Traceback (most recent call last):
484 SyntaxError: * argument may appear only once
485
486 >>> def foo(a,b,/,c,*b,c,*d,*e,c):
487 ... pass
488 Traceback (most recent call last):
489 SyntaxError: * argument may appear only once
490
491 >>> def foo(a,b,/,c,*b,c,*d,**e):
492 ... pass
493 Traceback (most recent call last):
494 SyntaxError: * argument may appear only once
495
496 >>> def foo(a=1,/*,b,c):
497 ... pass
498 Traceback (most recent call last):
499 SyntaxError: expected comma between / and *
500
501 >>> def foo(a=1,d=,c):
502 ... pass
503 Traceback (most recent call last):
504 SyntaxError: expected default value expression
505
506 >>> def foo(a,d=,c):
507 ... pass
508 Traceback (most recent call last):
509 SyntaxError: expected default value expression
510
511 >>> def foo(a,d: int=,c):
512 ... pass
513 Traceback (most recent call last):
514 SyntaxError: expected default value expression
515
516 >>> lambda /,a,b,c: None
517 Traceback (most recent call last):
518 SyntaxError: at least one argument must precede /
519
520 >>> lambda a,/,/,b,c: None
521 Traceback (most recent call last):
522 SyntaxError: / may appear only once
523
524 >>> lambda a,/,a1,/,b,c: None
525 Traceback (most recent call last):
526 SyntaxError: / may appear only once
527
528 >>> lambda a=1,/,/,*b,/,c: None
529 Traceback (most recent call last):
530 SyntaxError: / may appear only once
531
532 >>> lambda a,/,a1=1,/,b,c: None
533 Traceback (most recent call last):
534 SyntaxError: / may appear only once
535
536 >>> lambda a,*b,c,/,d,e: None
537 Traceback (most recent call last):
538 SyntaxError: / must be ahead of *
539
540 >>> lambda a=1,*b,c=3,/,d,e: None
541 Traceback (most recent call last):
542 SyntaxError: / must be ahead of *
543
544 >>> lambda a=1,/*,b,c: None
545 Traceback (most recent call last):
546 SyntaxError: expected comma between / and *
547
548 >>> lambda a,*b=3,c: None
549 Traceback (most recent call last):
550 SyntaxError: var-positional argument cannot have default value
551
552 >>> lambda a,**b=3: None
553 Traceback (most recent call last):
554 SyntaxError: var-keyword argument cannot have default value
555
556 >>> lambda a, *a, b, **c, d: None
557 Traceback (most recent call last):
558 SyntaxError: arguments cannot follow var-keyword argument
559
560 >>> lambda a,*a, b, **c, d=4: None
561 Traceback (most recent call last):
562 SyntaxError: arguments cannot follow var-keyword argument
563
564 >>> lambda a,*a, b, **c, *d: None
565 Traceback (most recent call last):
566 SyntaxError: arguments cannot follow var-keyword argument
567
568 >>> lambda a,*a, b, **c, **d: None
569 Traceback (most recent call last):
570 SyntaxError: arguments cannot follow var-keyword argument
571
572 >>> lambda a=1,/,**b,/,c: None
573 Traceback (most recent call last):
574 SyntaxError: arguments cannot follow var-keyword argument
575
576 >>> lambda *b,*d: None
577 Traceback (most recent call last):
578 SyntaxError: * argument may appear only once
579
580 >>> lambda a,*b,c,*d,*e,c: None
581 Traceback (most recent call last):
582 SyntaxError: * argument may appear only once
583
584 >>> lambda a,b,/,c,*b,c,*d,*e,c: None
585 Traceback (most recent call last):
586 SyntaxError: * argument may appear only once
587
588 >>> lambda a,b,/,c,*b,c,*d,**e: None
589 Traceback (most recent call last):
590 SyntaxError: * argument may appear only once
591
592 >>> lambda a=1,d=,c: None
593 Traceback (most recent call last):
594 SyntaxError: expected default value expression
595
596 >>> lambda a,d=,c: None
597 Traceback (most recent call last):
598 SyntaxError: expected default value expression
599
600 >>> lambda a,d=3,c: None
601 Traceback (most recent call last):
602 SyntaxError: parameter without a default follows parameter with a default
603
604 >>> lambda a,/,d=3,c: None
605 Traceback (most recent call last):
606 SyntaxError: parameter without a default follows parameter with a default
607
608 >>> import ast; ast.parse('''
609 ... def f(
610 ... *, # type: int
611 ... a, # type: int
612 ... ):
613 ... pass
614 ... ''', type_comments=True)
615 Traceback (most recent call last):
616 SyntaxError: bare * has associated type comment
617
618
619 From ast_for_funcdef():
620
621 >>> def None(x):
622 ... pass
623 Traceback (most recent call last):
624 SyntaxError: invalid syntax
625
626
627 From ast_for_call():
628
629 >>> def f(it, *varargs, **kwargs):
630 ... return list(it)
631 >>> L = range(10)
632 >>> f(x for x in L)
633 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
634 >>> f(x for x in L, 1)
635 Traceback (most recent call last):
636 SyntaxError: Generator expression must be parenthesized
637 >>> f(x for x in L, y=1)
638 Traceback (most recent call last):
639 SyntaxError: Generator expression must be parenthesized
640 >>> f(x for x in L, *[])
641 Traceback (most recent call last):
642 SyntaxError: Generator expression must be parenthesized
643 >>> f(x for x in L, **{})
644 Traceback (most recent call last):
645 SyntaxError: Generator expression must be parenthesized
646 >>> f(L, x for x in L)
647 Traceback (most recent call last):
648 SyntaxError: Generator expression must be parenthesized
649 >>> f(x for x in L, y for y in L)
650 Traceback (most recent call last):
651 SyntaxError: Generator expression must be parenthesized
652 >>> f(x for x in L,)
653 Traceback (most recent call last):
654 SyntaxError: Generator expression must be parenthesized
655 >>> f((x for x in L), 1)
656 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
657 >>> class C(x for x in L):
658 ... pass
659 Traceback (most recent call last):
660 SyntaxError: invalid syntax
661
662 >>> def g(*args, **kwargs):
663 ... print(args, sorted(kwargs.items()))
664 >>> g(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
665 ... 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
666 ... 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
667 ... 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
668 ... 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
669 ... 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
670 ... 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
671 ... 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
672 ... 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
673 ... 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
674 ... 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
675 ... 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
676 ... 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
677 ... 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
678 ... 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
679 ... 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
680 ... 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
681 ... 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275,
682 ... 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
683 ... 290, 291, 292, 293, 294, 295, 296, 297, 298, 299) # doctest: +ELLIPSIS
684 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299) []
685
686 >>> g(a000=0, a001=1, a002=2, a003=3, a004=4, a005=5, a006=6, a007=7, a008=8,
687 ... a009=9, a010=10, a011=11, a012=12, a013=13, a014=14, a015=15, a016=16,
688 ... a017=17, a018=18, a019=19, a020=20, a021=21, a022=22, a023=23, a024=24,
689 ... a025=25, a026=26, a027=27, a028=28, a029=29, a030=30, a031=31, a032=32,
690 ... a033=33, a034=34, a035=35, a036=36, a037=37, a038=38, a039=39, a040=40,
691 ... a041=41, a042=42, a043=43, a044=44, a045=45, a046=46, a047=47, a048=48,
692 ... a049=49, a050=50, a051=51, a052=52, a053=53, a054=54, a055=55, a056=56,
693 ... a057=57, a058=58, a059=59, a060=60, a061=61, a062=62, a063=63, a064=64,
694 ... a065=65, a066=66, a067=67, a068=68, a069=69, a070=70, a071=71, a072=72,
695 ... a073=73, a074=74, a075=75, a076=76, a077=77, a078=78, a079=79, a080=80,
696 ... a081=81, a082=82, a083=83, a084=84, a085=85, a086=86, a087=87, a088=88,
697 ... a089=89, a090=90, a091=91, a092=92, a093=93, a094=94, a095=95, a096=96,
698 ... a097=97, a098=98, a099=99, a100=100, a101=101, a102=102, a103=103,
699 ... a104=104, a105=105, a106=106, a107=107, a108=108, a109=109, a110=110,
700 ... a111=111, a112=112, a113=113, a114=114, a115=115, a116=116, a117=117,
701 ... a118=118, a119=119, a120=120, a121=121, a122=122, a123=123, a124=124,
702 ... a125=125, a126=126, a127=127, a128=128, a129=129, a130=130, a131=131,
703 ... a132=132, a133=133, a134=134, a135=135, a136=136, a137=137, a138=138,
704 ... a139=139, a140=140, a141=141, a142=142, a143=143, a144=144, a145=145,
705 ... a146=146, a147=147, a148=148, a149=149, a150=150, a151=151, a152=152,
706 ... a153=153, a154=154, a155=155, a156=156, a157=157, a158=158, a159=159,
707 ... a160=160, a161=161, a162=162, a163=163, a164=164, a165=165, a166=166,
708 ... a167=167, a168=168, a169=169, a170=170, a171=171, a172=172, a173=173,
709 ... a174=174, a175=175, a176=176, a177=177, a178=178, a179=179, a180=180,
710 ... a181=181, a182=182, a183=183, a184=184, a185=185, a186=186, a187=187,
711 ... a188=188, a189=189, a190=190, a191=191, a192=192, a193=193, a194=194,
712 ... a195=195, a196=196, a197=197, a198=198, a199=199, a200=200, a201=201,
713 ... a202=202, a203=203, a204=204, a205=205, a206=206, a207=207, a208=208,
714 ... a209=209, a210=210, a211=211, a212=212, a213=213, a214=214, a215=215,
715 ... a216=216, a217=217, a218=218, a219=219, a220=220, a221=221, a222=222,
716 ... a223=223, a224=224, a225=225, a226=226, a227=227, a228=228, a229=229,
717 ... a230=230, a231=231, a232=232, a233=233, a234=234, a235=235, a236=236,
718 ... a237=237, a238=238, a239=239, a240=240, a241=241, a242=242, a243=243,
719 ... a244=244, a245=245, a246=246, a247=247, a248=248, a249=249, a250=250,
720 ... a251=251, a252=252, a253=253, a254=254, a255=255, a256=256, a257=257,
721 ... a258=258, a259=259, a260=260, a261=261, a262=262, a263=263, a264=264,
722 ... a265=265, a266=266, a267=267, a268=268, a269=269, a270=270, a271=271,
723 ... a272=272, a273=273, a274=274, a275=275, a276=276, a277=277, a278=278,
724 ... a279=279, a280=280, a281=281, a282=282, a283=283, a284=284, a285=285,
725 ... a286=286, a287=287, a288=288, a289=289, a290=290, a291=291, a292=292,
726 ... a293=293, a294=294, a295=295, a296=296, a297=297, a298=298, a299=299)
727 ... # doctest: +ELLIPSIS
728 () [('a000', 0), ('a001', 1), ('a002', 2), ..., ('a298', 298), ('a299', 299)]
729
730 >>> class C:
731 ... def meth(self, *args):
732 ... return args
733 >>> obj = C()
734 >>> obj.meth(
735 ... 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
736 ... 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
737 ... 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
738 ... 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
739 ... 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
740 ... 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
741 ... 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
742 ... 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
743 ... 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
744 ... 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
745 ... 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
746 ... 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
747 ... 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
748 ... 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
749 ... 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
750 ... 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
751 ... 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
752 ... 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275,
753 ... 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
754 ... 290, 291, 292, 293, 294, 295, 296, 297, 298, 299) # doctest: +ELLIPSIS
755 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299)
756
757 >>> f(lambda x: x[0] = 3)
758 Traceback (most recent call last):
759 SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
760
761 # Check that this error doesn't trigger for names:
762 >>> f(a={x: for x in {}})
763 Traceback (most recent call last):
764 SyntaxError: invalid syntax
765
766 The grammar accepts any test (basically, any expression) in the
767 keyword slot of a call site. Test a few different options.
768
769 >>> f(x()=2)
770 Traceback (most recent call last):
771 SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
772 >>> f(a or b=1)
773 Traceback (most recent call last):
774 SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
775 >>> f(x.y=1)
776 Traceback (most recent call last):
777 SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
778 >>> f((x)=2)
779 Traceback (most recent call last):
780 SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
781 >>> f(True=1)
782 Traceback (most recent call last):
783 SyntaxError: cannot assign to True
784 >>> f(False=1)
785 Traceback (most recent call last):
786 SyntaxError: cannot assign to False
787 >>> f(None=1)
788 Traceback (most recent call last):
789 SyntaxError: cannot assign to None
790 >>> f(__debug__=1)
791 Traceback (most recent call last):
792 SyntaxError: cannot assign to __debug__
793 >>> __debug__: int
794 Traceback (most recent call last):
795 SyntaxError: cannot assign to __debug__
796 >>> f(a=)
797 Traceback (most recent call last):
798 SyntaxError: expected argument value expression
799 >>> f(a, b, c=)
800 Traceback (most recent call last):
801 SyntaxError: expected argument value expression
802 >>> f(a, b, c=, d)
803 Traceback (most recent call last):
804 SyntaxError: expected argument value expression
805 >>> f(*args=[0])
806 Traceback (most recent call last):
807 SyntaxError: cannot assign to iterable argument unpacking
808 >>> f(a, b, *args=[0])
809 Traceback (most recent call last):
810 SyntaxError: cannot assign to iterable argument unpacking
811 >>> f(**kwargs={'a': 1})
812 Traceback (most recent call last):
813 SyntaxError: cannot assign to keyword argument unpacking
814 >>> f(a, b, *args, **kwargs={'a': 1})
815 Traceback (most recent call last):
816 SyntaxError: cannot assign to keyword argument unpacking
817
818
819 More set_context():
820
821 >>> (x for x in x) += 1
822 Traceback (most recent call last):
823 SyntaxError: 'generator expression' is an illegal expression for augmented assignment
824 >>> None += 1
825 Traceback (most recent call last):
826 SyntaxError: 'None' is an illegal expression for augmented assignment
827 >>> __debug__ += 1
828 Traceback (most recent call last):
829 SyntaxError: cannot assign to __debug__
830 >>> f() += 1
831 Traceback (most recent call last):
832 SyntaxError: 'function call' is an illegal expression for augmented assignment
833
834
835 Test continue in finally in weird combinations.
836
837 continue in for loop under finally should be ok.
838
839 >>> def test():
840 ... try:
841 ... pass
842 ... finally:
843 ... for abc in range(10):
844 ... continue
845 ... print(abc)
846 >>> test()
847 9
848
849 continue in a finally should be ok.
850
851 >>> def test():
852 ... for abc in range(10):
853 ... try:
854 ... pass
855 ... finally:
856 ... continue
857 ... print(abc)
858 >>> test()
859 9
860
861 >>> def test():
862 ... for abc in range(10):
863 ... try:
864 ... pass
865 ... finally:
866 ... try:
867 ... continue
868 ... except:
869 ... pass
870 ... print(abc)
871 >>> test()
872 9
873
874 >>> def test():
875 ... for abc in range(10):
876 ... try:
877 ... pass
878 ... finally:
879 ... try:
880 ... pass
881 ... except:
882 ... continue
883 ... print(abc)
884 >>> test()
885 9
886
887 A continue outside loop should not be allowed.
888
889 >>> def foo():
890 ... try:
891 ... pass
892 ... finally:
893 ... continue
894 Traceback (most recent call last):
895 ...
896 SyntaxError: 'continue' not properly in loop
897
898 There is one test for a break that is not in a loop. The compiler
899 uses a single data structure to keep track of try-finally and loops,
900 so we need to be sure that a break is actually inside a loop. If it
901 isn't, there should be a syntax error.
902
903 >>> try:
904 ... print(1)
905 ... break
906 ... print(2)
907 ... finally:
908 ... print(3)
909 Traceback (most recent call last):
910 ...
911 SyntaxError: 'break' outside loop
912
913 Misuse of the nonlocal and global statement can lead to a few unique syntax errors.
914
915 >>> def f():
916 ... print(x)
917 ... global x
918 Traceback (most recent call last):
919 ...
920 SyntaxError: name 'x' is used prior to global declaration
921
922 >>> def f():
923 ... x = 1
924 ... global x
925 Traceback (most recent call last):
926 ...
927 SyntaxError: name 'x' is assigned to before global declaration
928
929 >>> def f(x):
930 ... global x
931 Traceback (most recent call last):
932 ...
933 SyntaxError: name 'x' is parameter and global
934
935 >>> def f():
936 ... x = 1
937 ... def g():
938 ... print(x)
939 ... nonlocal x
940 Traceback (most recent call last):
941 ...
942 SyntaxError: name 'x' is used prior to nonlocal declaration
943
944 >>> def f():
945 ... x = 1
946 ... def g():
947 ... x = 2
948 ... nonlocal x
949 Traceback (most recent call last):
950 ...
951 SyntaxError: name 'x' is assigned to before nonlocal declaration
952
953 >>> def f(x):
954 ... nonlocal x
955 Traceback (most recent call last):
956 ...
957 SyntaxError: name 'x' is parameter and nonlocal
958
959 >>> def f():
960 ... global x
961 ... nonlocal x
962 Traceback (most recent call last):
963 ...
964 SyntaxError: name 'x' is nonlocal and global
965
966 >>> def f():
967 ... nonlocal x
968 Traceback (most recent call last):
969 ...
970 SyntaxError: no binding for nonlocal 'x' found
971
972 From SF bug #1705365
973 >>> nonlocal x
974 Traceback (most recent call last):
975 ...
976 SyntaxError: nonlocal declaration not allowed at module level
977
978 From https://bugs.python.org/issue25973
979 >>> class A:
980 ... def f(self):
981 ... nonlocal __x
982 Traceback (most recent call last):
983 ...
984 SyntaxError: no binding for nonlocal '_A__x' found
985
986
987 This tests assignment-context; there was a bug in Python 2.5 where compiling
988 a complex 'if' (one with 'elif') would fail to notice an invalid suite,
989 leading to spurious errors.
990
991 >>> if 1:
992 ... x() = 1
993 ... elif 1:
994 ... pass
995 Traceback (most recent call last):
996 ...
997 SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
998
999 >>> if 1:
1000 ... pass
1001 ... elif 1:
1002 ... x() = 1
1003 Traceback (most recent call last):
1004 ...
1005 SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
1006
1007 >>> if 1:
1008 ... x() = 1
1009 ... elif 1:
1010 ... pass
1011 ... else:
1012 ... pass
1013 Traceback (most recent call last):
1014 ...
1015 SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
1016
1017 >>> if 1:
1018 ... pass
1019 ... elif 1:
1020 ... x() = 1
1021 ... else:
1022 ... pass
1023 Traceback (most recent call last):
1024 ...
1025 SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
1026
1027 >>> if 1:
1028 ... pass
1029 ... elif 1:
1030 ... pass
1031 ... else:
1032 ... x() = 1
1033 Traceback (most recent call last):
1034 ...
1035 SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
1036
1037 Missing ':' before suites:
1038
1039 >>> def f()
1040 ... pass
1041 Traceback (most recent call last):
1042 SyntaxError: expected ':'
1043
1044 >>> def f[T]()
1045 ... pass
1046 Traceback (most recent call last):
1047 SyntaxError: expected ':'
1048
1049 >>> class A
1050 ... pass
1051 Traceback (most recent call last):
1052 SyntaxError: expected ':'
1053
1054 >>> class A[T]
1055 ... pass
1056 Traceback (most recent call last):
1057 SyntaxError: expected ':'
1058
1059 >>> class A[T]()
1060 ... pass
1061 Traceback (most recent call last):
1062 SyntaxError: expected ':'
1063
1064 >>> class R&D:
1065 ... pass
1066 Traceback (most recent call last):
1067 SyntaxError: invalid syntax
1068
1069 >>> if 1
1070 ... pass
1071 ... elif 1:
1072 ... pass
1073 ... else:
1074 ... x() = 1
1075 Traceback (most recent call last):
1076 SyntaxError: expected ':'
1077
1078 >>> if 1:
1079 ... pass
1080 ... elif 1
1081 ... pass
1082 ... else:
1083 ... x() = 1
1084 Traceback (most recent call last):
1085 SyntaxError: expected ':'
1086
1087 >>> if 1:
1088 ... pass
1089 ... elif 1:
1090 ... pass
1091 ... else
1092 ... x() = 1
1093 Traceback (most recent call last):
1094 SyntaxError: expected ':'
1095
1096 >>> for x in range(10)
1097 ... pass
1098 Traceback (most recent call last):
1099 SyntaxError: expected ':'
1100
1101 >>> for x in range 10:
1102 ... pass
1103 Traceback (most recent call last):
1104 SyntaxError: invalid syntax
1105
1106 >>> while True
1107 ... pass
1108 Traceback (most recent call last):
1109 SyntaxError: expected ':'
1110
1111 >>> with blech as something
1112 ... pass
1113 Traceback (most recent call last):
1114 SyntaxError: expected ':'
1115
1116 >>> with blech
1117 ... pass
1118 Traceback (most recent call last):
1119 SyntaxError: expected ':'
1120
1121 >>> with blech, block as something
1122 ... pass
1123 Traceback (most recent call last):
1124 SyntaxError: expected ':'
1125
1126 >>> with blech, block as something, bluch
1127 ... pass
1128 Traceback (most recent call last):
1129 SyntaxError: expected ':'
1130
1131 >>> with (blech as something)
1132 ... pass
1133 Traceback (most recent call last):
1134 SyntaxError: expected ':'
1135
1136 >>> with (blech)
1137 ... pass
1138 Traceback (most recent call last):
1139 SyntaxError: expected ':'
1140
1141 >>> with (blech, block as something)
1142 ... pass
1143 Traceback (most recent call last):
1144 SyntaxError: expected ':'
1145
1146 >>> with (blech, block as something, bluch)
1147 ... pass
1148 Traceback (most recent call last):
1149 SyntaxError: expected ':'
1150
1151 >>> with block ad something:
1152 ... pass
1153 Traceback (most recent call last):
1154 SyntaxError: invalid syntax
1155
1156 >>> try
1157 ... pass
1158 Traceback (most recent call last):
1159 SyntaxError: expected ':'
1160
1161 >>> try:
1162 ... pass
1163 ... except
1164 ... pass
1165 Traceback (most recent call last):
1166 SyntaxError: expected ':'
1167
1168 >>> match x
1169 ... case list():
1170 ... pass
1171 Traceback (most recent call last):
1172 SyntaxError: expected ':'
1173
1174 >>> match x x:
1175 ... case list():
1176 ... pass
1177 Traceback (most recent call last):
1178 SyntaxError: invalid syntax
1179
1180 >>> match x:
1181 ... case list()
1182 ... pass
1183 Traceback (most recent call last):
1184 SyntaxError: expected ':'
1185
1186 >>> match x:
1187 ... case [y] if y > 0
1188 ... pass
1189 Traceback (most recent call last):
1190 SyntaxError: expected ':'
1191
1192 >>> if x = 3:
1193 ... pass
1194 Traceback (most recent call last):
1195 SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1196
1197 >>> while x = 3:
1198 ... pass
1199 Traceback (most recent call last):
1200 SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1201
1202 >>> if x.a = 3:
1203 ... pass
1204 Traceback (most recent call last):
1205 SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
1206
1207 >>> while x.a = 3:
1208 ... pass
1209 Traceback (most recent call last):
1210 SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
1211
1212
1213 Missing parens after function definition
1214
1215 >>> def f:
1216 Traceback (most recent call last):
1217 SyntaxError: expected '('
1218
1219 >>> async def f:
1220 Traceback (most recent call last):
1221 SyntaxError: expected '('
1222
1223 >>> def f -> int:
1224 Traceback (most recent call last):
1225 SyntaxError: expected '('
1226
1227 >>> async def f -> int: # type: int
1228 Traceback (most recent call last):
1229 SyntaxError: expected '('
1230
1231 >>> async def f[T]:
1232 Traceback (most recent call last):
1233 SyntaxError: expected '('
1234
1235 >>> def f[T] -> str:
1236 Traceback (most recent call last):
1237 SyntaxError: expected '('
1238
1239 Parenthesized arguments in function definitions
1240
1241 >>> def f(x, (y, z), w):
1242 ... pass
1243 Traceback (most recent call last):
1244 SyntaxError: Function parameters cannot be parenthesized
1245
1246 >>> def f((x, y, z, w)):
1247 ... pass
1248 Traceback (most recent call last):
1249 SyntaxError: Function parameters cannot be parenthesized
1250
1251 >>> def f(x, (y, z, w)):
1252 ... pass
1253 Traceback (most recent call last):
1254 SyntaxError: Function parameters cannot be parenthesized
1255
1256 >>> def f((x, y, z), w):
1257 ... pass
1258 Traceback (most recent call last):
1259 SyntaxError: Function parameters cannot be parenthesized
1260
1261 >>> lambda x, (y, z), w: None
1262 Traceback (most recent call last):
1263 SyntaxError: Lambda expression parameters cannot be parenthesized
1264
1265 >>> lambda (x, y, z, w): None
1266 Traceback (most recent call last):
1267 SyntaxError: Lambda expression parameters cannot be parenthesized
1268
1269 >>> lambda x, (y, z, w): None
1270 Traceback (most recent call last):
1271 SyntaxError: Lambda expression parameters cannot be parenthesized
1272
1273 >>> lambda (x, y, z), w: None
1274 Traceback (most recent call last):
1275 SyntaxError: Lambda expression parameters cannot be parenthesized
1276
1277 Custom error messages for try blocks that are not followed by except/finally
1278
1279 >>> try:
1280 ... x = 34
1281 ...
1282 Traceback (most recent call last):
1283 SyntaxError: expected 'except' or 'finally' block
1284
1285 Custom error message for try block mixing except and except*
1286
1287 >>> try:
1288 ... pass
1289 ... except TypeError:
1290 ... pass
1291 ... except* ValueError:
1292 ... pass
1293 Traceback (most recent call last):
1294 SyntaxError: cannot have both 'except' and 'except*' on the same 'try'
1295
1296 >>> try:
1297 ... pass
1298 ... except* TypeError:
1299 ... pass
1300 ... except ValueError:
1301 ... pass
1302 Traceback (most recent call last):
1303 SyntaxError: cannot have both 'except' and 'except*' on the same 'try'
1304
1305 >>> try:
1306 ... pass
1307 ... except TypeError:
1308 ... pass
1309 ... except TypeError:
1310 ... pass
1311 ... except* ValueError:
1312 ... pass
1313 Traceback (most recent call last):
1314 SyntaxError: cannot have both 'except' and 'except*' on the same 'try'
1315
1316 >>> try:
1317 ... pass
1318 ... except* TypeError:
1319 ... pass
1320 ... except* TypeError:
1321 ... pass
1322 ... except ValueError:
1323 ... pass
1324 Traceback (most recent call last):
1325 SyntaxError: cannot have both 'except' and 'except*' on the same 'try'
1326
1327 Ensure that early = are not matched by the parser as invalid comparisons
1328 >>> f(2, 4, x=34); 1 $ 2
1329 Traceback (most recent call last):
1330 SyntaxError: invalid syntax
1331
1332 >>> dict(x=34); x $ y
1333 Traceback (most recent call last):
1334 SyntaxError: invalid syntax
1335
1336 >>> dict(x=34, (x for x in range 10), 1); x $ y
1337 Traceback (most recent call last):
1338 SyntaxError: invalid syntax
1339
1340 >>> dict(x=34, x=1, y=2); x $ y
1341 Traceback (most recent call last):
1342 SyntaxError: invalid syntax
1343
1344 Incomplete dictionary literals
1345
1346 >>> {1:2, 3:4, 5}
1347 Traceback (most recent call last):
1348 SyntaxError: ':' expected after dictionary key
1349
1350 >>> {1:2, 3:4, 5:}
1351 Traceback (most recent call last):
1352 SyntaxError: expression expected after dictionary key and ':'
1353
1354 >>> {1: *12+1, 23: 1}
1355 Traceback (most recent call last):
1356 SyntaxError: cannot use a starred expression in a dictionary value
1357
1358 >>> {1: *12+1}
1359 Traceback (most recent call last):
1360 SyntaxError: cannot use a starred expression in a dictionary value
1361
1362 >>> {1: 23, 1: *12+1}
1363 Traceback (most recent call last):
1364 SyntaxError: cannot use a starred expression in a dictionary value
1365
1366 >>> {1:}
1367 Traceback (most recent call last):
1368 SyntaxError: expression expected after dictionary key and ':'
1369
1370 # Ensure that the error is not raised for syntax errors that happen after sets
1371
1372 >>> {1} $
1373 Traceback (most recent call last):
1374 SyntaxError: invalid syntax
1375
1376 # Ensure that the error is not raised for invalid expressions
1377
1378 >>> {1: 2, 3: foo(,), 4: 5}
1379 Traceback (most recent call last):
1380 SyntaxError: invalid syntax
1381
1382 >>> {1: $, 2: 3}
1383 Traceback (most recent call last):
1384 SyntaxError: invalid syntax
1385
1386 Specialized indentation errors:
1387
1388 >>> while condition:
1389 ... pass
1390 Traceback (most recent call last):
1391 IndentationError: expected an indented block after 'while' statement on line 1
1392
1393 >>> for x in range(10):
1394 ... pass
1395 Traceback (most recent call last):
1396 IndentationError: expected an indented block after 'for' statement on line 1
1397
1398 >>> for x in range(10):
1399 ... pass
1400 ... else:
1401 ... pass
1402 Traceback (most recent call last):
1403 IndentationError: expected an indented block after 'else' statement on line 3
1404
1405 >>> async for x in range(10):
1406 ... pass
1407 Traceback (most recent call last):
1408 IndentationError: expected an indented block after 'for' statement on line 1
1409
1410 >>> async for x in range(10):
1411 ... pass
1412 ... else:
1413 ... pass
1414 Traceback (most recent call last):
1415 IndentationError: expected an indented block after 'else' statement on line 3
1416
1417 >>> if something:
1418 ... pass
1419 Traceback (most recent call last):
1420 IndentationError: expected an indented block after 'if' statement on line 1
1421
1422 >>> if something:
1423 ... pass
1424 ... elif something_else:
1425 ... pass
1426 Traceback (most recent call last):
1427 IndentationError: expected an indented block after 'elif' statement on line 3
1428
1429 >>> if something:
1430 ... pass
1431 ... elif something_else:
1432 ... pass
1433 ... else:
1434 ... pass
1435 Traceback (most recent call last):
1436 IndentationError: expected an indented block after 'else' statement on line 5
1437
1438 >>> try:
1439 ... pass
1440 Traceback (most recent call last):
1441 IndentationError: expected an indented block after 'try' statement on line 1
1442
1443 >>> try:
1444 ... something()
1445 ... except:
1446 ... pass
1447 Traceback (most recent call last):
1448 IndentationError: expected an indented block after 'except' statement on line 3
1449
1450 >>> try:
1451 ... something()
1452 ... except A:
1453 ... pass
1454 Traceback (most recent call last):
1455 IndentationError: expected an indented block after 'except' statement on line 3
1456
1457 >>> try:
1458 ... something()
1459 ... except* A:
1460 ... pass
1461 Traceback (most recent call last):
1462 IndentationError: expected an indented block after 'except*' statement on line 3
1463
1464 >>> try:
1465 ... something()
1466 ... except A:
1467 ... pass
1468 ... finally:
1469 ... pass
1470 Traceback (most recent call last):
1471 IndentationError: expected an indented block after 'finally' statement on line 5
1472
1473 >>> try:
1474 ... something()
1475 ... except* A:
1476 ... pass
1477 ... finally:
1478 ... pass
1479 Traceback (most recent call last):
1480 IndentationError: expected an indented block after 'finally' statement on line 5
1481
1482 >>> with A:
1483 ... pass
1484 Traceback (most recent call last):
1485 IndentationError: expected an indented block after 'with' statement on line 1
1486
1487 >>> with A as a, B as b:
1488 ... pass
1489 Traceback (most recent call last):
1490 IndentationError: expected an indented block after 'with' statement on line 1
1491
1492 >>> with (A as a, B as b):
1493 ... pass
1494 Traceback (most recent call last):
1495 IndentationError: expected an indented block after 'with' statement on line 1
1496
1497 >>> async with A:
1498 ... pass
1499 Traceback (most recent call last):
1500 IndentationError: expected an indented block after 'with' statement on line 1
1501
1502 >>> async with A as a, B as b:
1503 ... pass
1504 Traceback (most recent call last):
1505 IndentationError: expected an indented block after 'with' statement on line 1
1506
1507 >>> async with (A as a, B as b):
1508 ... pass
1509 Traceback (most recent call last):
1510 IndentationError: expected an indented block after 'with' statement on line 1
1511
1512 >>> def foo(x, /, y, *, z=2):
1513 ... pass
1514 Traceback (most recent call last):
1515 IndentationError: expected an indented block after function definition on line 1
1516
1517 >>> def foo[T](x, /, y, *, z=2):
1518 ... pass
1519 Traceback (most recent call last):
1520 IndentationError: expected an indented block after function definition on line 1
1521
1522 >>> class Blech(A):
1523 ... pass
1524 Traceback (most recent call last):
1525 IndentationError: expected an indented block after class definition on line 1
1526
1527 >>> class Blech[T](A):
1528 ... pass
1529 Traceback (most recent call last):
1530 IndentationError: expected an indented block after class definition on line 1
1531
1532 >>> match something:
1533 ... pass
1534 Traceback (most recent call last):
1535 IndentationError: expected an indented block after 'match' statement on line 1
1536
1537 >>> match something:
1538 ... case []:
1539 ... pass
1540 Traceback (most recent call last):
1541 IndentationError: expected an indented block after 'case' statement on line 2
1542
1543 >>> match something:
1544 ... case []:
1545 ... ...
1546 ... case {}:
1547 ... pass
1548 Traceback (most recent call last):
1549 IndentationError: expected an indented block after 'case' statement on line 4
1550
1551 Make sure that the old "raise X, Y[, Z]" form is gone:
1552 >>> raise X, Y
1553 Traceback (most recent call last):
1554 ...
1555 SyntaxError: invalid syntax
1556 >>> raise X, Y, Z
1557 Traceback (most recent call last):
1558 ...
1559 SyntaxError: invalid syntax
1560
1561 Check that an multiple exception types with missing parentheses
1562 raise a custom exception
1563
1564 >>> try:
1565 ... pass
1566 ... except A, B:
1567 ... pass
1568 Traceback (most recent call last):
1569 SyntaxError: multiple exception types must be parenthesized
1570
1571 >>> try:
1572 ... pass
1573 ... except A, B, C:
1574 ... pass
1575 Traceback (most recent call last):
1576 SyntaxError: multiple exception types must be parenthesized
1577
1578 >>> try:
1579 ... pass
1580 ... except A, B, C as blech:
1581 ... pass
1582 Traceback (most recent call last):
1583 SyntaxError: multiple exception types must be parenthesized
1584
1585 >>> try:
1586 ... pass
1587 ... except A, B, C as blech:
1588 ... pass
1589 ... finally:
1590 ... pass
1591 Traceback (most recent call last):
1592 SyntaxError: multiple exception types must be parenthesized
1593
1594
1595 >>> try:
1596 ... pass
1597 ... except* A, B:
1598 ... pass
1599 Traceback (most recent call last):
1600 SyntaxError: multiple exception types must be parenthesized
1601
1602 >>> try:
1603 ... pass
1604 ... except* A, B, C:
1605 ... pass
1606 Traceback (most recent call last):
1607 SyntaxError: multiple exception types must be parenthesized
1608
1609 >>> try:
1610 ... pass
1611 ... except* A, B, C as blech:
1612 ... pass
1613 Traceback (most recent call last):
1614 SyntaxError: multiple exception types must be parenthesized
1615
1616 >>> try:
1617 ... pass
1618 ... except* A, B, C as blech:
1619 ... pass
1620 ... finally:
1621 ... pass
1622 Traceback (most recent call last):
1623 SyntaxError: multiple exception types must be parenthesized
1624
1625 Custom exception for 'except*' without an exception type
1626
1627 >>> try:
1628 ... pass
1629 ... except* A as a:
1630 ... pass
1631 ... except*:
1632 ... pass
1633 Traceback (most recent call last):
1634 SyntaxError: expected one or more exception types
1635
1636
1637 >>> f(a=23, a=234)
1638 Traceback (most recent call last):
1639 ...
1640 SyntaxError: keyword argument repeated: a
1641
1642 >>> {1, 2, 3} = 42
1643 Traceback (most recent call last):
1644 SyntaxError: cannot assign to set display here. Maybe you meant '==' instead of '='?
1645
1646 >>> {1: 2, 3: 4} = 42
1647 Traceback (most recent call last):
1648 SyntaxError: cannot assign to dict literal here. Maybe you meant '==' instead of '='?
1649
1650 >>> f'{x}' = 42
1651 Traceback (most recent call last):
1652 SyntaxError: cannot assign to f-string expression here. Maybe you meant '==' instead of '='?
1653
1654 >>> f'{x}-{y}' = 42
1655 Traceback (most recent call last):
1656 SyntaxError: cannot assign to f-string expression here. Maybe you meant '==' instead of '='?
1657
1658 >>> (x, y, z=3, d, e)
1659 Traceback (most recent call last):
1660 SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1661
1662 >>> [x, y, z=3, d, e]
1663 Traceback (most recent call last):
1664 SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1665
1666 >>> [z=3]
1667 Traceback (most recent call last):
1668 SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1669
1670 >>> {x, y, z=3, d, e}
1671 Traceback (most recent call last):
1672 SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1673
1674 >>> {z=3}
1675 Traceback (most recent call last):
1676 SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1677
1678 >>> from t import x,
1679 Traceback (most recent call last):
1680 SyntaxError: trailing comma not allowed without surrounding parentheses
1681
1682 >>> from t import x,y,
1683 Traceback (most recent call last):
1684 SyntaxError: trailing comma not allowed without surrounding parentheses
1685
1686 >>> import a from b
1687 Traceback (most recent call last):
1688 SyntaxError: Did you mean to use 'from ... import ...' instead?
1689
1690 >>> import a.y.z from b.y.z
1691 Traceback (most recent call last):
1692 SyntaxError: Did you mean to use 'from ... import ...' instead?
1693
1694 >>> import a from b as bar
1695 Traceback (most recent call last):
1696 SyntaxError: Did you mean to use 'from ... import ...' instead?
1697
1698 >>> import a.y.z from b.y.z as bar
1699 Traceback (most recent call last):
1700 SyntaxError: Did you mean to use 'from ... import ...' instead?
1701
1702 >>> import a, b,c from b
1703 Traceback (most recent call last):
1704 SyntaxError: Did you mean to use 'from ... import ...' instead?
1705
1706 >>> import a.y.z, b.y.z, c.y.z from b.y.z
1707 Traceback (most recent call last):
1708 SyntaxError: Did you mean to use 'from ... import ...' instead?
1709
1710 >>> import a,b,c from b as bar
1711 Traceback (most recent call last):
1712 SyntaxError: Did you mean to use 'from ... import ...' instead?
1713
1714 >>> import a.y.z, b.y.z, c.y.z from b.y.z as bar
1715 Traceback (most recent call last):
1716 SyntaxError: Did you mean to use 'from ... import ...' instead?
1717
1718 # Check that we dont raise the "trailing comma" error if there is more
1719 # input to the left of the valid part that we parsed.
1720
1721 >>> from t import x,y, and 3
1722 Traceback (most recent call last):
1723 SyntaxError: invalid syntax
1724
1725 >>> from i import
1726 Traceback (most recent call last):
1727 SyntaxError: Expected one or more names after 'import'
1728
1729 >>> from .. import
1730 Traceback (most recent call last):
1731 SyntaxError: Expected one or more names after 'import'
1732
1733 >>> import
1734 Traceback (most recent call last):
1735 SyntaxError: Expected one or more names after 'import'
1736
1737 >>> (): int
1738 Traceback (most recent call last):
1739 SyntaxError: only single target (not tuple) can be annotated
1740 >>> []: int
1741 Traceback (most recent call last):
1742 SyntaxError: only single target (not list) can be annotated
1743 >>> (()): int
1744 Traceback (most recent call last):
1745 SyntaxError: only single target (not tuple) can be annotated
1746 >>> ([]): int
1747 Traceback (most recent call last):
1748 SyntaxError: only single target (not list) can be annotated
1749
1750 # 'not' after operators:
1751
1752 >>> 3 + not 3
1753 Traceback (most recent call last):
1754 SyntaxError: 'not' after an operator must be parenthesized
1755
1756 >>> 3 * not 3
1757 Traceback (most recent call last):
1758 SyntaxError: 'not' after an operator must be parenthesized
1759
1760 >>> + not 3
1761 Traceback (most recent call last):
1762 SyntaxError: 'not' after an operator must be parenthesized
1763
1764 >>> - not 3
1765 Traceback (most recent call last):
1766 SyntaxError: 'not' after an operator must be parenthesized
1767
1768 >>> ~ not 3
1769 Traceback (most recent call last):
1770 SyntaxError: 'not' after an operator must be parenthesized
1771
1772 >>> 3 + - not 3
1773 Traceback (most recent call last):
1774 SyntaxError: 'not' after an operator must be parenthesized
1775
1776 >>> 3 + not -1
1777 Traceback (most recent call last):
1778 SyntaxError: 'not' after an operator must be parenthesized
1779
1780 # Check that we don't introduce misleading errors
1781 >>> not 1 */ 2
1782 Traceback (most recent call last):
1783 SyntaxError: invalid syntax
1784
1785 >>> not 1 +
1786 Traceback (most recent call last):
1787 SyntaxError: invalid syntax
1788
1789 >>> not + 1 +
1790 Traceback (most recent call last):
1791 SyntaxError: invalid syntax
1792
1793 Corner-cases that used to fail to raise the correct error:
1794
1795 >>> def f(*, x=lambda __debug__:0): pass
1796 Traceback (most recent call last):
1797 SyntaxError: cannot assign to __debug__
1798
1799 >>> def f(*args:(lambda __debug__:0)): pass
1800 Traceback (most recent call last):
1801 SyntaxError: cannot assign to __debug__
1802
1803 >>> def f(**kwargs:(lambda __debug__:0)): pass
1804 Traceback (most recent call last):
1805 SyntaxError: cannot assign to __debug__
1806
1807 >>> with (lambda *:0): pass
1808 Traceback (most recent call last):
1809 SyntaxError: named arguments must follow bare *
1810
1811 Corner-cases that used to crash:
1812
1813 >>> def f(**__debug__): pass
1814 Traceback (most recent call last):
1815 SyntaxError: cannot assign to __debug__
1816
1817 >>> def f(*xx, __debug__): pass
1818 Traceback (most recent call last):
1819 SyntaxError: cannot assign to __debug__
1820
1821 >>> import ä £
1822 Traceback (most recent call last):
1823 SyntaxError: invalid character '£' (U+00A3)
1824
1825 Invalid pattern matching constructs:
1826
1827 >>> match ...:
1828 ... case 42 as _:
1829 ... ...
1830 Traceback (most recent call last):
1831 SyntaxError: cannot use '_' as a target
1832
1833 >>> match ...:
1834 ... case 42 as 1+2+4:
1835 ... ...
1836 Traceback (most recent call last):
1837 SyntaxError: invalid pattern target
1838
1839 >>> match ...:
1840 ... case Foo(z=1, y=2, x):
1841 ... ...
1842 Traceback (most recent call last):
1843 SyntaxError: positional patterns follow keyword patterns
1844
1845 >>> match ...:
1846 ... case Foo(a, z=1, y=2, x):
1847 ... ...
1848 Traceback (most recent call last):
1849 SyntaxError: positional patterns follow keyword patterns
1850
1851 >>> match ...:
1852 ... case Foo(z=1, x, y=2):
1853 ... ...
1854 Traceback (most recent call last):
1855 SyntaxError: positional patterns follow keyword patterns
1856
1857 >>> match ...:
1858 ... case C(a=b, c, d=e, f, g=h, i, j=k, ...):
1859 ... ...
1860 Traceback (most recent call last):
1861 SyntaxError: positional patterns follow keyword patterns
1862
1863 Uses of the star operator which should fail:
1864
1865 A[:*b]
1866
1867 >>> A[:*b]
1868 Traceback (most recent call last):
1869 ...
1870 SyntaxError: invalid syntax
1871 >>> A[:(*b)]
1872 Traceback (most recent call last):
1873 ...
1874 SyntaxError: cannot use starred expression here
1875 >>> A[:*b] = 1
1876 Traceback (most recent call last):
1877 ...
1878 SyntaxError: invalid syntax
1879 >>> del A[:*b]
1880 Traceback (most recent call last):
1881 ...
1882 SyntaxError: invalid syntax
1883
1884 A[*b:]
1885
1886 >>> A[*b:]
1887 Traceback (most recent call last):
1888 ...
1889 SyntaxError: invalid syntax
1890 >>> A[(*b):]
1891 Traceback (most recent call last):
1892 ...
1893 SyntaxError: cannot use starred expression here
1894 >>> A[*b:] = 1
1895 Traceback (most recent call last):
1896 ...
1897 SyntaxError: invalid syntax
1898 >>> del A[*b:]
1899 Traceback (most recent call last):
1900 ...
1901 SyntaxError: invalid syntax
1902
1903 A[*b:*b]
1904
1905 >>> A[*b:*b]
1906 Traceback (most recent call last):
1907 ...
1908 SyntaxError: invalid syntax
1909 >>> A[(*b:*b)]
1910 Traceback (most recent call last):
1911 ...
1912 SyntaxError: invalid syntax
1913 >>> A[*b:*b] = 1
1914 Traceback (most recent call last):
1915 ...
1916 SyntaxError: invalid syntax
1917 >>> del A[*b:*b]
1918 Traceback (most recent call last):
1919 ...
1920 SyntaxError: invalid syntax
1921
1922 A[*(1:2)]
1923
1924 >>> A[*(1:2)]
1925 Traceback (most recent call last):
1926 ...
1927 SyntaxError: Invalid star expression
1928 >>> A[*(1:2)] = 1
1929 Traceback (most recent call last):
1930 ...
1931 SyntaxError: Invalid star expression
1932 >>> del A[*(1:2)]
1933 Traceback (most recent call last):
1934 ...
1935 SyntaxError: Invalid star expression
1936
1937 A[*:] and A[:*]
1938
1939 >>> A[*:]
1940 Traceback (most recent call last):
1941 ...
1942 SyntaxError: Invalid star expression
1943 >>> A[:*]
1944 Traceback (most recent call last):
1945 ...
1946 SyntaxError: invalid syntax
1947
1948 A[*]
1949
1950 >>> A[*]
1951 Traceback (most recent call last):
1952 ...
1953 SyntaxError: Invalid star expression
1954
1955 A[**]
1956
1957 >>> A[**]
1958 Traceback (most recent call last):
1959 ...
1960 SyntaxError: invalid syntax
1961
1962 A[**b]
1963
1964 >>> A[**b]
1965 Traceback (most recent call last):
1966 ...
1967 SyntaxError: invalid syntax
1968 >>> A[**b] = 1
1969 Traceback (most recent call last):
1970 ...
1971 SyntaxError: invalid syntax
1972 >>> del A[**b]
1973 Traceback (most recent call last):
1974 ...
1975 SyntaxError: invalid syntax
1976
1977 def f(x: *b)
1978
1979 >>> def f6(x: *b): pass
1980 Traceback (most recent call last):
1981 ...
1982 SyntaxError: invalid syntax
1983 >>> def f7(x: *b = 1): pass
1984 Traceback (most recent call last):
1985 ...
1986 SyntaxError: invalid syntax
1987
1988 **kwargs: *a
1989
1990 >>> def f8(**kwargs: *a): pass
1991 Traceback (most recent call last):
1992 ...
1993 SyntaxError: invalid syntax
1994
1995 x: *b
1996
1997 >>> x: *b
1998 Traceback (most recent call last):
1999 ...
2000 SyntaxError: invalid syntax
2001 >>> x: *b = 1
2002 Traceback (most recent call last):
2003 ...
2004 SyntaxError: invalid syntax
2005
2006 Invalid bytes literals:
2007
2008 >>> b"Ä€"
2009 Traceback (most recent call last):
2010 ...
2011 b"Ä€"
2012 ^^^
2013 SyntaxError: bytes can only contain ASCII literal characters
2014
2015 >>> b"абвгде"
2016 Traceback (most recent call last):
2017 ...
2018 b"абвгде"
2019 ^^^^^^^^
2020 SyntaxError: bytes can only contain ASCII literal characters
2021
2022 >>> b"abc ъющый" # first 3 letters are ascii
2023 Traceback (most recent call last):
2024 ...
2025 b"abc ъющый"
2026 ^^^^^^^^^^^
2027 SyntaxError: bytes can only contain ASCII literal characters
2028
2029 Invalid expressions in type scopes:
2030
2031 >>> type A[] = int
2032 Traceback (most recent call last):
2033 ...
2034 SyntaxError: Type parameter list cannot be empty
2035
2036 >>> class A[]: ...
2037 Traceback (most recent call last):
2038 ...
2039 SyntaxError: Type parameter list cannot be empty
2040
2041 >>> def some[](): ...
2042 Traceback (most recent call last):
2043 ...
2044 SyntaxError: Type parameter list cannot be empty
2045
2046 >>> def some[]()
2047 Traceback (most recent call last):
2048 ...
2049 SyntaxError: Type parameter list cannot be empty
2050
2051 >>> async def some[]: # type: int
2052 Traceback (most recent call last):
2053 ...
2054 SyntaxError: Type parameter list cannot be empty
2055
2056 >>> def f[T: (x:=3)](): pass
2057 Traceback (most recent call last):
2058 ...
2059 SyntaxError: named expression cannot be used within a TypeVar bound
2060
2061 >>> def f[T: ((x:= 3), int)](): pass
2062 Traceback (most recent call last):
2063 ...
2064 SyntaxError: named expression cannot be used within a TypeVar constraint
2065
2066 >>> def f[T = ((x:=3))](): pass
2067 Traceback (most recent call last):
2068 ...
2069 SyntaxError: named expression cannot be used within a TypeVar default
2070
2071 >>> async def f[T: (x:=3)](): pass
2072 Traceback (most recent call last):
2073 ...
2074 SyntaxError: named expression cannot be used within a TypeVar bound
2075
2076 >>> async def f[T: ((x:= 3), int)](): pass
2077 Traceback (most recent call last):
2078 ...
2079 SyntaxError: named expression cannot be used within a TypeVar constraint
2080
2081 >>> async def f[T = ((x:=3))](): pass
2082 Traceback (most recent call last):
2083 ...
2084 SyntaxError: named expression cannot be used within a TypeVar default
2085
2086 >>> type A[T: (x:=3)] = int
2087 Traceback (most recent call last):
2088 ...
2089 SyntaxError: named expression cannot be used within a TypeVar bound
2090
2091 >>> type A[T: ((x:= 3), int)] = int
2092 Traceback (most recent call last):
2093 ...
2094 SyntaxError: named expression cannot be used within a TypeVar constraint
2095
2096 >>> type A[T = ((x:=3))] = int
2097 Traceback (most recent call last):
2098 ...
2099 SyntaxError: named expression cannot be used within a TypeVar default
2100
2101 >>> def f[T: (yield)](): pass
2102 Traceback (most recent call last):
2103 ...
2104 SyntaxError: yield expression cannot be used within a TypeVar bound
2105
2106 >>> def f[T: (int, (yield))](): pass
2107 Traceback (most recent call last):
2108 ...
2109 SyntaxError: yield expression cannot be used within a TypeVar constraint
2110
2111 >>> def f[T = (yield)](): pass
2112 Traceback (most recent call last):
2113 ...
2114 SyntaxError: yield expression cannot be used within a TypeVar default
2115
2116 >>> def f[*Ts = (yield)](): pass
2117 Traceback (most recent call last):
2118 ...
2119 SyntaxError: yield expression cannot be used within a TypeVarTuple default
2120
2121 >>> def f[**P = [(yield), int]](): pass
2122 Traceback (most recent call last):
2123 ...
2124 SyntaxError: yield expression cannot be used within a ParamSpec default
2125
2126 >>> type A[T: (yield 3)] = int
2127 Traceback (most recent call last):
2128 ...
2129 SyntaxError: yield expression cannot be used within a TypeVar bound
2130
2131 >>> type A[T: (int, (yield 3))] = int
2132 Traceback (most recent call last):
2133 ...
2134 SyntaxError: yield expression cannot be used within a TypeVar constraint
2135
2136 >>> type A[T = (yield 3)] = int
2137 Traceback (most recent call last):
2138 ...
2139 SyntaxError: yield expression cannot be used within a TypeVar default
2140
2141 >>> type A[T: (await 3)] = int
2142 Traceback (most recent call last):
2143 ...
2144 SyntaxError: await expression cannot be used within a TypeVar bound
2145
2146 >>> type A[T: (yield from [])] = int
2147 Traceback (most recent call last):
2148 ...
2149 SyntaxError: yield expression cannot be used within a TypeVar bound
2150
2151 >>> class A[T: (yield 3)]: pass
2152 Traceback (most recent call last):
2153 ...
2154 SyntaxError: yield expression cannot be used within a TypeVar bound
2155
2156 >>> class A[T: (int, (yield 3))]: pass
2157 Traceback (most recent call last):
2158 ...
2159 SyntaxError: yield expression cannot be used within a TypeVar constraint
2160
2161 >>> class A[T = (yield)]: pass
2162 Traceback (most recent call last):
2163 ...
2164 SyntaxError: yield expression cannot be used within a TypeVar default
2165
2166 >>> class A[*Ts = (yield)]: pass
2167 Traceback (most recent call last):
2168 ...
2169 SyntaxError: yield expression cannot be used within a TypeVarTuple default
2170
2171 >>> class A[**P = [(yield), int]]: pass
2172 Traceback (most recent call last):
2173 ...
2174 SyntaxError: yield expression cannot be used within a ParamSpec default
2175
2176 >>> type A = (x := 3)
2177 Traceback (most recent call last):
2178 ...
2179 SyntaxError: named expression cannot be used within a type alias
2180
2181 >>> type A = (yield 3)
2182 Traceback (most recent call last):
2183 ...
2184 SyntaxError: yield expression cannot be used within a type alias
2185
2186 >>> type A = (await 3)
2187 Traceback (most recent call last):
2188 ...
2189 SyntaxError: await expression cannot be used within a type alias
2190
2191 >>> type A = (yield from [])
2192 Traceback (most recent call last):
2193 ...
2194 SyntaxError: yield expression cannot be used within a type alias
2195
2196 >>> class A[T]((x := 3)): ...
2197 Traceback (most recent call last):
2198 ...
2199 SyntaxError: named expression cannot be used within the definition of a generic
2200
2201 >>> class A[T]((yield 3)): ...
2202 Traceback (most recent call last):
2203 ...
2204 SyntaxError: yield expression cannot be used within the definition of a generic
2205
2206 >>> class A[T]((await 3)): ...
2207 Traceback (most recent call last):
2208 ...
2209 SyntaxError: await expression cannot be used within the definition of a generic
2210
2211 >>> class A[T]((yield from [])): ...
2212 Traceback (most recent call last):
2213 ...
2214 SyntaxError: yield expression cannot be used within the definition of a generic
2215
2216 >>> f(**x, *y)
2217 Traceback (most recent call last):
2218 SyntaxError: iterable argument unpacking follows keyword argument unpacking
2219
2220 >>> f(**x, *)
2221 Traceback (most recent call last):
2222 SyntaxError: Invalid star expression
2223
2224 >>> f(x, *:)
2225 Traceback (most recent call last):
2226 SyntaxError: Invalid star expression
2227
2228 >>> f(x, *)
2229 Traceback (most recent call last):
2230 SyntaxError: Invalid star expression
2231
2232 >>> f(x = 5, *)
2233 Traceback (most recent call last):
2234 SyntaxError: Invalid star expression
2235
2236 >>> f(x = 5, *:)
2237 Traceback (most recent call last):
2238 SyntaxError: Invalid star expression
2239 """
2240
2241 import re
2242 import doctest
2243 import textwrap
2244 import unittest
2245
2246 from test import support
2247
2248 class SyntaxTestCase(unittest.TestCase):
2249
2250 def _check_error(self, code, errtext,
2251 filename="<testcase>", mode="exec", subclass=None,
2252 lineno=None, offset=None, end_lineno=None, end_offset=None):
2253 """Check that compiling code raises SyntaxError with errtext.
2254
2255 errtest is a regular expression that must be present in the
2256 test of the exception raised. If subclass is specified it
2257 is the expected subclass of SyntaxError (e.g. IndentationError).
2258 """
2259 try:
2260 compile(code, filename, mode)
2261 except SyntaxError as err:
2262 if subclass and not isinstance(err, subclass):
2263 self.fail("SyntaxError is not a %s" % subclass.__name__)
2264 mo = re.search(errtext, str(err))
2265 if mo is None:
2266 self.fail("SyntaxError did not contain %r" % (errtext,))
2267 self.assertEqual(err.filename, filename)
2268 if lineno is not None:
2269 self.assertEqual(err.lineno, lineno)
2270 if offset is not None:
2271 self.assertEqual(err.offset, offset)
2272 if end_lineno is not None:
2273 self.assertEqual(err.end_lineno, end_lineno)
2274 if end_offset is not None:
2275 self.assertEqual(err.end_offset, end_offset)
2276
2277 else:
2278 self.fail("compile() did not raise SyntaxError")
2279
2280 def test_expression_with_assignment(self):
2281 self._check_error(
2282 "print(end1 + end2 = ' ')",
2283 'expression cannot contain assignment, perhaps you meant "=="?',
2284 offset=7
2285 )
2286
2287 def test_curly_brace_after_primary_raises_immediately(self):
2288 self._check_error("f{}", "invalid syntax", mode="single")
2289
2290 def test_assign_call(self):
2291 self._check_error("f() = 1", "assign")
2292
2293 def test_assign_del(self):
2294 self._check_error("del (,)", "invalid syntax")
2295 self._check_error("del 1", "cannot delete literal")
2296 self._check_error("del (1, 2)", "cannot delete literal")
2297 self._check_error("del None", "cannot delete None")
2298 self._check_error("del *x", "cannot delete starred")
2299 self._check_error("del (*x)", "cannot use starred expression")
2300 self._check_error("del (*x,)", "cannot delete starred")
2301 self._check_error("del [*x,]", "cannot delete starred")
2302 self._check_error("del f()", "cannot delete function call")
2303 self._check_error("del f(a, b)", "cannot delete function call")
2304 self._check_error("del o.f()", "cannot delete function call")
2305 self._check_error("del a[0]()", "cannot delete function call")
2306 self._check_error("del x, f()", "cannot delete function call")
2307 self._check_error("del f(), x", "cannot delete function call")
2308 self._check_error("del [a, b, ((c), (d,), e.f())]", "cannot delete function call")
2309 self._check_error("del (a if True else b)", "cannot delete conditional")
2310 self._check_error("del +a", "cannot delete expression")
2311 self._check_error("del a, +b", "cannot delete expression")
2312 self._check_error("del a + b", "cannot delete expression")
2313 self._check_error("del (a + b, c)", "cannot delete expression")
2314 self._check_error("del (c[0], a + b)", "cannot delete expression")
2315 self._check_error("del a.b.c + 2", "cannot delete expression")
2316 self._check_error("del a.b.c[0] + 2", "cannot delete expression")
2317 self._check_error("del (a, b, (c, d.e.f + 2))", "cannot delete expression")
2318 self._check_error("del [a, b, (c, d.e.f[0] + 2)]", "cannot delete expression")
2319 self._check_error("del (a := 5)", "cannot delete named expression")
2320 # We don't have a special message for this, but make sure we don't
2321 # report "cannot delete name"
2322 self._check_error("del a += b", "invalid syntax")
2323
2324 def test_global_param_err_first(self):
2325 source = """if 1:
2326 def error(a):
2327 global a # SyntaxError
2328 def error2():
2329 b = 1
2330 global b # SyntaxError
2331 """
2332 self._check_error(source, "parameter and global", lineno=3)
2333
2334 def test_nonlocal_param_err_first(self):
2335 source = """if 1:
2336 def error(a):
2337 nonlocal a # SyntaxError
2338 def error2():
2339 b = 1
2340 global b # SyntaxError
2341 """
2342 self._check_error(source, "parameter and nonlocal", lineno=3)
2343
2344 def test_yield_outside_function(self):
2345 self._check_error("if 0: yield", "outside function")
2346 self._check_error("if 0: yield\nelse: x=1", "outside function")
2347 self._check_error("if 1: pass\nelse: yield", "outside function")
2348 self._check_error("while 0: yield", "outside function")
2349 self._check_error("while 0: yield\nelse: x=1", "outside function")
2350 self._check_error("class C:\n if 0: yield", "outside function")
2351 self._check_error("class C:\n if 1: pass\n else: yield",
2352 "outside function")
2353 self._check_error("class C:\n while 0: yield", "outside function")
2354 self._check_error("class C:\n while 0: yield\n else: x = 1",
2355 "outside function")
2356
2357 def test_return_outside_function(self):
2358 self._check_error("if 0: return", "outside function")
2359 self._check_error("if 0: return\nelse: x=1", "outside function")
2360 self._check_error("if 1: pass\nelse: return", "outside function")
2361 self._check_error("while 0: return", "outside function")
2362 self._check_error("class C:\n if 0: return", "outside function")
2363 self._check_error("class C:\n while 0: return", "outside function")
2364 self._check_error("class C:\n while 0: return\n else: x=1",
2365 "outside function")
2366 self._check_error("class C:\n if 0: return\n else: x= 1",
2367 "outside function")
2368 self._check_error("class C:\n if 1: pass\n else: return",
2369 "outside function")
2370
2371 def test_break_outside_loop(self):
2372 msg = "outside loop"
2373 self._check_error("break", msg, lineno=1)
2374 self._check_error("if 0: break", msg, lineno=1)
2375 self._check_error("if 0: break\nelse: x=1", msg, lineno=1)
2376 self._check_error("if 1: pass\nelse: break", msg, lineno=2)
2377 self._check_error("class C:\n if 0: break", msg, lineno=2)
2378 self._check_error("class C:\n if 1: pass\n else: break",
2379 msg, lineno=3)
2380 self._check_error("with object() as obj:\n break",
2381 msg, lineno=2)
2382
2383 def test_continue_outside_loop(self):
2384 msg = "not properly in loop"
2385 self._check_error("if 0: continue", msg, lineno=1)
2386 self._check_error("if 0: continue\nelse: x=1", msg, lineno=1)
2387 self._check_error("if 1: pass\nelse: continue", msg, lineno=2)
2388 self._check_error("class C:\n if 0: continue", msg, lineno=2)
2389 self._check_error("class C:\n if 1: pass\n else: continue",
2390 msg, lineno=3)
2391 self._check_error("with object() as obj:\n continue",
2392 msg, lineno=2)
2393
2394 def test_unexpected_indent(self):
2395 self._check_error("foo()\n bar()\n", "unexpected indent",
2396 subclass=IndentationError)
2397
2398 def test_no_indent(self):
2399 self._check_error("if 1:\nfoo()", "expected an indented block",
2400 subclass=IndentationError)
2401
2402 def test_bad_outdent(self):
2403 self._check_error("if 1:\n foo()\n bar()",
2404 "unindent does not match .* level",
2405 subclass=IndentationError)
2406
2407 def test_kwargs_last(self):
2408 self._check_error("int(base=10, '2')",
2409 "positional argument follows keyword argument")
2410
2411 def test_kwargs_last2(self):
2412 self._check_error("int(**{'base': 10}, '2')",
2413 "positional argument follows "
2414 "keyword argument unpacking")
2415
2416 def test_kwargs_last3(self):
2417 self._check_error("int(**{'base': 10}, *['2'])",
2418 "iterable argument unpacking follows "
2419 "keyword argument unpacking")
2420
2421 def test_generator_in_function_call(self):
2422 self._check_error("foo(x, y for y in range(3) for z in range(2) if z , p)",
2423 "Generator expression must be parenthesized",
2424 lineno=1, end_lineno=1, offset=11, end_offset=53)
2425
2426 def test_except_then_except_star(self):
2427 self._check_error("try: pass\nexcept ValueError: pass\nexcept* TypeError: pass",
2428 r"cannot have both 'except' and 'except\*' on the same 'try'",
2429 lineno=3, end_lineno=3, offset=1, end_offset=8)
2430
2431 def test_except_star_then_except(self):
2432 self._check_error("try: pass\nexcept* ValueError: pass\nexcept TypeError: pass",
2433 r"cannot have both 'except' and 'except\*' on the same 'try'",
2434 lineno=3, end_lineno=3, offset=1, end_offset=7)
2435
2436 def test_empty_line_after_linecont(self):
2437 # See issue-40847
2438 s = r"""\
2439 pass
2440 \
2441
2442 pass
2443 """
2444 try:
2445 compile(s, '<string>', 'exec')
2446 except SyntaxError:
2447 self.fail("Empty line after a line continuation character is valid.")
2448
2449 # See issue-46091
2450 s1 = r"""\
2451 def fib(n):
2452 \
2453 '''Print a Fibonacci series up to n.'''
2454 \
2455 a, b = 0, 1
2456 """
2457 s2 = r"""\
2458 def fib(n):
2459 '''Print a Fibonacci series up to n.'''
2460 a, b = 0, 1
2461 """
2462 try:
2463 compile(s1, '<string>', 'exec')
2464 compile(s2, '<string>', 'exec')
2465 except SyntaxError:
2466 self.fail("Indented statement over multiple lines is valid")
2467
2468 def test_continuation_bad_indentation(self):
2469 # Check that code that breaks indentation across multiple lines raises a syntax error
2470
2471 code = r"""\
2472 if x:
2473 y = 1
2474 \
2475 foo = 1
2476 """
2477
2478 self.assertRaises(IndentationError, exec, code)
2479
2480 @support.cpython_only
2481 def test_disallowed_type_param_names(self):
2482 # See gh-128632
2483
2484 self._check_error(f"class A[__classdict__]: pass",
2485 f"reserved name '__classdict__' cannot be used for type parameter")
2486 self._check_error(f"def f[__classdict__](): pass",
2487 f"reserved name '__classdict__' cannot be used for type parameter")
2488 self._check_error(f"type T[__classdict__] = tuple[__classdict__]",
2489 f"reserved name '__classdict__' cannot be used for type parameter")
2490
2491 # These compilations are here to make sure __class__, __classcell__ and __classdictcell__
2492 # don't break in the future like __classdict__ did in this case.
2493 for name in ('__class__', '__classcell__', '__classdictcell__'):
2494 compile(f"""
2495 class A:
2496 class B[{name}]: pass
2497 """, "<testcase>", mode="exec")
2498
2499 @support.cpython_only
2500 def test_nested_named_except_blocks(self):
2501 code = ""
2502 for i in range(12):
2503 code += f"{' '*i}try:\n"
2504 code += f"{' '*(i+1)}raise Exception\n"
2505 code += f"{' '*i}except Exception as e:\n"
2506 code += f"{' '*4*12}pass"
2507 self._check_error(code, "too many statically nested blocks")
2508
2509 @support.cpython_only
2510 def test_with_statement_many_context_managers(self):
2511 # See gh-113297
2512
2513 def get_code(n):
2514 code = textwrap.dedent("""
2515 def bug():
2516 with (
2517 a
2518 """)
2519 for i in range(n):
2520 code += f" as a{i}, a\n"
2521 code += "): yield a"
2522 return code
2523
2524 CO_MAXBLOCKS = 21 # static nesting limit of the compiler
2525 MAX_MANAGERS = CO_MAXBLOCKS - 1 # One for the StopIteration block
2526
2527 for n in range(MAX_MANAGERS):
2528 with self.subTest(f"within range: {n=}"):
2529 compile(get_code(n), "<string>", "exec")
2530
2531 for n in range(MAX_MANAGERS, MAX_MANAGERS + 5):
2532 with self.subTest(f"out of range: {n=}"):
2533 self._check_error(get_code(n), "too many statically nested blocks")
2534
2535 @support.cpython_only
2536 def test_async_with_statement_many_context_managers(self):
2537 # See gh-116767
2538
2539 def get_code(n):
2540 code = [ textwrap.dedent("""
2541 async def bug():
2542 async with (
2543 a
2544 """) ]
2545 for i in range(n):
2546 code.append(f" as a{i}, a\n")
2547 code.append("): yield a")
2548 return "".join(code)
2549
2550 CO_MAXBLOCKS = 21 # static nesting limit of the compiler
2551 MAX_MANAGERS = CO_MAXBLOCKS - 1 # One for the StopIteration block
2552
2553 for n in range(MAX_MANAGERS):
2554 with self.subTest(f"within range: {n=}"):
2555 compile(get_code(n), "<string>", "exec")
2556
2557 for n in range(MAX_MANAGERS, MAX_MANAGERS + 5):
2558 with self.subTest(f"out of range: {n=}"):
2559 self._check_error(get_code(n), "too many statically nested blocks")
2560
2561 def test_barry_as_flufl_with_syntax_errors(self):
2562 # The "barry_as_flufl" rule can produce some "bugs-at-a-distance" if
2563 # is reading the wrong token in the presence of syntax errors later
2564 # in the file. See bpo-42214 for more information.
2565 code = """
2566 def func1():
2567 if a != b:
2568 raise ValueError
2569
2570 def func2():
2571 try
2572 return 1
2573 finally:
2574 pass
2575 """
2576 self._check_error(code, "expected ':'")
2577
2578 def test_invalid_line_continuation_error_position(self):
2579 self._check_error(r"a = 3 \ 4",
2580 "unexpected character after line continuation character",
2581 lineno=1, offset=8)
2582 self._check_error('1,\\#\n2',
2583 "unexpected character after line continuation character",
2584 lineno=1, offset=4)
2585 self._check_error('\nfgdfgf\n1,\\#\n2\n',
2586 "unexpected character after line continuation character",
2587 lineno=3, offset=4)
2588
2589 def test_invalid_line_continuation_left_recursive(self):
2590 # Check bpo-42218: SyntaxErrors following left-recursive rules
2591 # (t_primary_raw in this case) need to be tested explicitly
2592 self._check_error("A.\u018a\\ ",
2593 "unexpected character after line continuation character")
2594 self._check_error("A.\u03bc\\\n",
2595 "unexpected EOF while parsing")
2596
2597 def test_error_parenthesis(self):
2598 for paren in "([{":
2599 self._check_error(paren + "1 + 2", f"\\{paren}' was never closed")
2600
2601 for paren in "([{":
2602 self._check_error(f"a = {paren} 1, 2, 3\nb=3", f"\\{paren}' was never closed")
2603
2604 for paren in ")]}":
2605 self._check_error(paren + "1 + 2", f"unmatched '\\{paren}'")
2606
2607 # Some more complex examples:
2608 code = """\
2609 func(
2610 a=["unclosed], # Need a quote in this comment: "
2611 b=2,
2612 )
2613 """
2614 self._check_error(code, "parenthesis '\\)' does not match opening parenthesis '\\['")
2615
2616 self._check_error("match y:\n case e(e=v,v,", " was never closed")
2617
2618 # Examples with dencodings
2619 s = b'# coding=latin\n(aaaaaaaaaaaaaaaaa\naaaaaaaaaaa\xb5'
2620 self._check_error(s, r"'\(' was never closed")
2621
2622 def test_error_string_literal(self):
2623
2624 self._check_error("'blech", r"unterminated string literal \(.*\)$")
2625 self._check_error('"blech', r"unterminated string literal \(.*\)$")
2626 self._check_error(
2627 r'"blech\"', r"unterminated string literal \(.*\); perhaps you escaped the end quote"
2628 )
2629 self._check_error(
2630 r'r"blech\"', r"unterminated string literal \(.*\); perhaps you escaped the end quote"
2631 )
2632 self._check_error("'''blech", "unterminated triple-quoted string literal")
2633 self._check_error('"""blech', "unterminated triple-quoted string literal")
2634
2635 def test_invisible_characters(self):
2636 self._check_error('print\x17("Hello")', "invalid non-printable character")
2637 self._check_error(b"with(0,,):\n\x01", "invalid non-printable character")
2638
2639 def test_match_call_does_not_raise_syntax_error(self):
2640 code = """
2641 def match(x):
2642 return 1+1
2643
2644 match(34)
2645 """
2646 compile(code, "<string>", "exec")
2647
2648 def test_case_call_does_not_raise_syntax_error(self):
2649 code = """
2650 def case(x):
2651 return 1+1
2652
2653 case(34)
2654 """
2655 compile(code, "<string>", "exec")
2656
2657 def test_multiline_compiler_error_points_to_the_end(self):
2658 self._check_error(
2659 "call(\na=1,\na=1\n)",
2660 "keyword argument repeated",
2661 lineno=3
2662 )
2663
2664 @support.cpython_only
2665 def test_syntax_error_on_deeply_nested_blocks(self):
2666 # This raises a SyntaxError, it used to raise a SystemError. Context
2667 # for this change can be found on issue #27514
2668
2669 # In 2.5 there was a missing exception and an assert was triggered in a
2670 # debug build. The number of blocks must be greater than CO_MAXBLOCKS.
2671 # SF #1565514
2672
2673 source = """
2674 while 1:
2675 while 2:
2676 while 3:
2677 while 4:
2678 while 5:
2679 while 6:
2680 while 8:
2681 while 9:
2682 while 10:
2683 while 11:
2684 while 12:
2685 while 13:
2686 while 14:
2687 while 15:
2688 while 16:
2689 while 17:
2690 while 18:
2691 while 19:
2692 while 20:
2693 while 21:
2694 while 22:
2695 while 23:
2696 break
2697 """
2698 self._check_error(source, "too many statically nested blocks")
2699
2700 @support.cpython_only
2701 def test_error_on_parser_stack_overflow(self):
2702 source = "-" * 100000 + "4"
2703 for mode in ["exec", "eval", "single"]:
2704 with self.subTest(mode=mode):
2705 with self.assertRaisesRegex(MemoryError, r"too complex"):
2706 compile(source, "<string>", mode)
2707
2708 @support.cpython_only
2709 def test_deep_invalid_rule(self):
2710 # Check that a very deep invalid rule in the PEG
2711 # parser doesn't have exponential backtracking.
2712 source = "d{{{{{{{{{{{{{{{{{{{{{{{{{```{{{{{{{ef f():y"
2713 with self.assertRaises(SyntaxError):
2714 compile(source, "<string>", "exec")
2715
2716
2717 def load_tests(loader, tests, pattern):
2718 tests.addTest(doctest.DocTestSuite())
2719 return tests
2720
2721
2722 if __name__ == "__main__":
2723 unittest.main()