test_syntax.py 65 KB

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