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