Debian Codegraph @

lib-python/3/test/test_syntax.py

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