ast.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835
  1. """
  2. ast
  3. ~~~
  4. The `ast` module helps Python applications to process trees of the Python
  5. abstract syntax grammar. The abstract syntax itself might change with
  6. each Python release; this module helps to find out programmatically what
  7. the current grammar looks like and allows modifications of it.
  8. An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
  9. a flag to the `compile()` builtin function or by using the `parse()`
  10. function from this module. The result will be a tree of objects whose
  11. classes all inherit from `ast.AST`.
  12. A modified abstract syntax tree can be compiled into a Python code object
  13. using the built-in `compile()` function.
  14. Additionally various helper functions are provided that make working with
  15. the trees simpler. The main intention of the helper functions and this
  16. module in general is to provide an easy to use interface for libraries
  17. that work tightly with the python syntax (template engines for example).
  18. :copyright: Copyright 2008 by Armin Ronacher.
  19. :license: Python License.
  20. """
  21. import sys
  22. import re
  23. from _ast import *
  24. from contextlib import contextmanager, nullcontext
  25. from enum import IntEnum, auto, _simple_enum
  26. def parse(source, filename='<unknown>', mode='exec', *,
  27. type_comments=False, feature_version=None):
  28. """
  29. Parse the source into an AST node.
  30. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
  31. Pass type_comments=True to get back type comments where the syntax allows.
  32. """
  33. flags = PyCF_ONLY_AST
  34. if type_comments:
  35. flags |= PyCF_TYPE_COMMENTS
  36. if feature_version is None:
  37. feature_version = -1
  38. elif isinstance(feature_version, tuple):
  39. major, minor = feature_version # Should be a 2-tuple.
  40. if major != 3:
  41. raise ValueError(f"Unsupported major version: {major}")
  42. feature_version = minor
  43. # Else it should be an int giving the minor version for 3.x.
  44. return compile(source, filename, mode, flags,
  45. _feature_version=feature_version)
  46. def literal_eval(node_or_string):
  47. """
  48. Evaluate an expression node or a string containing only a Python
  49. expression. The string or node provided may only consist of the following
  50. Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
  51. sets, booleans, and None.
  52. Caution: A complex expression can overflow the C stack and cause a crash.
  53. """
  54. if isinstance(node_or_string, str):
  55. node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval')
  56. if isinstance(node_or_string, Expression):
  57. node_or_string = node_or_string.body
  58. def _raise_malformed_node(node):
  59. msg = "malformed node or string"
  60. if lno := getattr(node, 'lineno', None):
  61. msg += f' on line {lno}'
  62. raise ValueError(msg + f': {node!r}')
  63. def _convert_num(node):
  64. if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
  65. _raise_malformed_node(node)
  66. return node.value
  67. def _convert_signed_num(node):
  68. if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
  69. operand = _convert_num(node.operand)
  70. if isinstance(node.op, UAdd):
  71. return + operand
  72. else:
  73. return - operand
  74. return _convert_num(node)
  75. def _convert(node):
  76. if isinstance(node, Constant):
  77. return node.value
  78. elif isinstance(node, Tuple):
  79. return tuple(map(_convert, node.elts))
  80. elif isinstance(node, List):
  81. return list(map(_convert, node.elts))
  82. elif isinstance(node, Set):
  83. return set(map(_convert, node.elts))
  84. elif (isinstance(node, Call) and isinstance(node.func, Name) and
  85. node.func.id == 'set' and node.args == node.keywords == []):
  86. return set()
  87. elif isinstance(node, Dict):
  88. if len(node.keys) != len(node.values):
  89. _raise_malformed_node(node)
  90. return dict(zip(map(_convert, node.keys),
  91. map(_convert, node.values)))
  92. elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
  93. left = _convert_signed_num(node.left)
  94. right = _convert_num(node.right)
  95. if isinstance(left, (int, float)) and isinstance(right, complex):
  96. if isinstance(node.op, Add):
  97. return left + right
  98. else:
  99. return left - right
  100. return _convert_signed_num(node)
  101. return _convert(node_or_string)
  102. def dump(node, annotate_fields=True, include_attributes=False, *, indent=None):
  103. """
  104. Return a formatted dump of the tree in node. This is mainly useful for
  105. debugging purposes. If annotate_fields is true (by default),
  106. the returned string will show the names and the values for fields.
  107. If annotate_fields is false, the result string will be more compact by
  108. omitting unambiguous field names. Attributes such as line
  109. numbers and column offsets are not dumped by default. If this is wanted,
  110. include_attributes can be set to true. If indent is a non-negative
  111. integer or string, then the tree will be pretty-printed with that indent
  112. level. None (the default) selects the single line representation.
  113. """
  114. def _format(node, level=0):
  115. if indent is not None:
  116. level += 1
  117. prefix = '\n' + indent * level
  118. sep = ',\n' + indent * level
  119. else:
  120. prefix = ''
  121. sep = ', '
  122. if isinstance(node, AST):
  123. cls = type(node)
  124. args = []
  125. allsimple = True
  126. keywords = annotate_fields
  127. for name in node._fields:
  128. try:
  129. value = getattr(node, name)
  130. except AttributeError:
  131. keywords = True
  132. continue
  133. if value is None and getattr(cls, name, ...) is None:
  134. keywords = True
  135. continue
  136. value, simple = _format(value, level)
  137. allsimple = allsimple and simple
  138. if keywords:
  139. args.append('%s=%s' % (name, value))
  140. else:
  141. args.append(value)
  142. if include_attributes and node._attributes:
  143. for name in node._attributes:
  144. try:
  145. value = getattr(node, name)
  146. except AttributeError:
  147. continue
  148. if value is None and getattr(cls, name, ...) is None:
  149. continue
  150. value, simple = _format(value, level)
  151. allsimple = allsimple and simple
  152. args.append('%s=%s' % (name, value))
  153. if allsimple and len(args) <= 3:
  154. return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args
  155. return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False
  156. elif isinstance(node, list):
  157. if not node:
  158. return '[]', True
  159. return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False
  160. return repr(node), True
  161. if not isinstance(node, AST):
  162. raise TypeError('expected AST, got %r' % node.__class__.__name__)
  163. if indent is not None and not isinstance(indent, str):
  164. indent = ' ' * indent
  165. return _format(node)[0]
  166. def copy_location(new_node, old_node):
  167. """
  168. Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
  169. attributes) from *old_node* to *new_node* if possible, and return *new_node*.
  170. """
  171. for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
  172. if attr in old_node._attributes and attr in new_node._attributes:
  173. value = getattr(old_node, attr, None)
  174. # end_lineno and end_col_offset are optional attributes, and they
  175. # should be copied whether the value is None or not.
  176. if value is not None or (
  177. hasattr(old_node, attr) and attr.startswith("end_")
  178. ):
  179. setattr(new_node, attr, value)
  180. return new_node
  181. def fix_missing_locations(node):
  182. """
  183. When you compile a node tree with compile(), the compiler expects lineno and
  184. col_offset attributes for every node that supports them. This is rather
  185. tedious to fill in for generated nodes, so this helper adds these attributes
  186. recursively where not already set, by setting them to the values of the
  187. parent node. It works recursively starting at *node*.
  188. """
  189. def _fix(node, lineno, col_offset, end_lineno, end_col_offset):
  190. if 'lineno' in node._attributes:
  191. if not hasattr(node, 'lineno'):
  192. node.lineno = lineno
  193. else:
  194. lineno = node.lineno
  195. if 'end_lineno' in node._attributes:
  196. if getattr(node, 'end_lineno', None) is None:
  197. node.end_lineno = end_lineno
  198. else:
  199. end_lineno = node.end_lineno
  200. if 'col_offset' in node._attributes:
  201. if not hasattr(node, 'col_offset'):
  202. node.col_offset = col_offset
  203. else:
  204. col_offset = node.col_offset
  205. if 'end_col_offset' in node._attributes:
  206. if getattr(node, 'end_col_offset', None) is None:
  207. node.end_col_offset = end_col_offset
  208. else:
  209. end_col_offset = node.end_col_offset
  210. for child in iter_child_nodes(node):
  211. _fix(child, lineno, col_offset, end_lineno, end_col_offset)
  212. _fix(node, 1, 0, 1, 0)
  213. return node
  214. def increment_lineno(node, n=1):
  215. """
  216. Increment the line number and end line number of each node in the tree
  217. starting at *node* by *n*. This is useful to "move code" to a different
  218. location in a file.
  219. """
  220. for child in walk(node):
  221. # TypeIgnore is a special case where lineno is not an attribute
  222. # but rather a field of the node itself.
  223. if isinstance(child, TypeIgnore):
  224. child.lineno = getattr(child, 'lineno', 0) + n
  225. continue
  226. if 'lineno' in child._attributes:
  227. child.lineno = getattr(child, 'lineno', 0) + n
  228. if (
  229. "end_lineno" in child._attributes
  230. and (end_lineno := getattr(child, "end_lineno", 0)) is not None
  231. ):
  232. child.end_lineno = end_lineno + n
  233. return node
  234. def iter_fields(node):
  235. """
  236. Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
  237. that is present on *node*.
  238. """
  239. for field in node._fields:
  240. try:
  241. yield field, getattr(node, field)
  242. except AttributeError:
  243. pass
  244. def iter_child_nodes(node):
  245. """
  246. Yield all direct child nodes of *node*, that is, all fields that are nodes
  247. and all items of fields that are lists of nodes.
  248. """
  249. for name, field in iter_fields(node):
  250. if isinstance(field, AST):
  251. yield field
  252. elif isinstance(field, list):
  253. for item in field:
  254. if isinstance(item, AST):
  255. yield item
  256. def get_docstring(node, clean=True):
  257. """
  258. Return the docstring for the given node or None if no docstring can
  259. be found. If the node provided does not have docstrings a TypeError
  260. will be raised.
  261. If *clean* is `True`, all tabs are expanded to spaces and any whitespace
  262. that can be uniformly removed from the second line onwards is removed.
  263. """
  264. if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
  265. raise TypeError("%r can't have docstrings" % node.__class__.__name__)
  266. if not(node.body and isinstance(node.body[0], Expr)):
  267. return None
  268. node = node.body[0].value
  269. if isinstance(node, Constant) and isinstance(node.value, str):
  270. text = node.value
  271. else:
  272. return None
  273. if clean:
  274. import inspect
  275. text = inspect.cleandoc(text)
  276. return text
  277. _line_pattern = re.compile(r"(.*?(?:\r\n|\n|\r|$))")
  278. def _splitlines_no_ff(source, maxlines=None):
  279. """Split a string into lines ignoring form feed and other chars.
  280. This mimics how the Python parser splits source code.
  281. """
  282. lines = []
  283. for lineno, match in enumerate(_line_pattern.finditer(source), 1):
  284. if maxlines is not None and lineno > maxlines:
  285. break
  286. lines.append(match[0])
  287. return lines
  288. def _pad_whitespace(source):
  289. r"""Replace all chars except '\f\t' in a line with spaces."""
  290. result = ''
  291. for c in source:
  292. if c in '\f\t':
  293. result += c
  294. else:
  295. result += ' '
  296. return result
  297. def get_source_segment(source, node, *, padded=False):
  298. """Get source code segment of the *source* that generated *node*.
  299. If some location information (`lineno`, `end_lineno`, `col_offset`,
  300. or `end_col_offset`) is missing, return None.
  301. If *padded* is `True`, the first line of a multi-line statement will
  302. be padded with spaces to match its original position.
  303. """
  304. try:
  305. if node.end_lineno is None or node.end_col_offset is None:
  306. return None
  307. lineno = node.lineno - 1
  308. end_lineno = node.end_lineno - 1
  309. col_offset = node.col_offset
  310. end_col_offset = node.end_col_offset
  311. except AttributeError:
  312. return None
  313. lines = _splitlines_no_ff(source, maxlines=end_lineno+1)
  314. if end_lineno == lineno:
  315. return lines[lineno].encode()[col_offset:end_col_offset].decode()
  316. if padded:
  317. padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())
  318. else:
  319. padding = ''
  320. first = padding + lines[lineno].encode()[col_offset:].decode()
  321. last = lines[end_lineno].encode()[:end_col_offset].decode()
  322. lines = lines[lineno+1:end_lineno]
  323. lines.insert(0, first)
  324. lines.append(last)
  325. return ''.join(lines)
  326. def walk(node):
  327. """
  328. Recursively yield all descendant nodes in the tree starting at *node*
  329. (including *node* itself), in no specified order. This is useful if you
  330. only want to modify nodes in place and don't care about the context.
  331. """
  332. from collections import deque
  333. todo = deque([node])
  334. while todo:
  335. node = todo.popleft()
  336. todo.extend(iter_child_nodes(node))
  337. yield node
  338. class NodeVisitor(object):
  339. """
  340. A node visitor base class that walks the abstract syntax tree and calls a
  341. visitor function for every node found. This function may return a value
  342. which is forwarded by the `visit` method.
  343. This class is meant to be subclassed, with the subclass adding visitor
  344. methods.
  345. Per default the visitor functions for the nodes are ``'visit_'`` +
  346. class name of the node. So a `TryFinally` node visit function would
  347. be `visit_TryFinally`. This behavior can be changed by overriding
  348. the `visit` method. If no visitor function exists for a node
  349. (return value `None`) the `generic_visit` visitor is used instead.
  350. Don't use the `NodeVisitor` if you want to apply changes to nodes during
  351. traversing. For this a special visitor exists (`NodeTransformer`) that
  352. allows modifications.
  353. """
  354. def visit(self, node):
  355. """Visit a node."""
  356. method = 'visit_' + node.__class__.__name__
  357. visitor = getattr(self, method, self.generic_visit)
  358. return visitor(node)
  359. def generic_visit(self, node):
  360. """Called if no explicit visitor function exists for a node."""
  361. for field, value in iter_fields(node):
  362. if isinstance(value, list):
  363. for item in value:
  364. if isinstance(item, AST):
  365. self.visit(item)
  366. elif isinstance(value, AST):
  367. self.visit(value)
  368. def visit_Constant(self, node):
  369. value = node.value
  370. type_name = _const_node_type_names.get(type(value))
  371. if type_name is None:
  372. for cls, name in _const_node_type_names.items():
  373. if isinstance(value, cls):
  374. type_name = name
  375. break
  376. if type_name is not None:
  377. method = 'visit_' + type_name
  378. try:
  379. visitor = getattr(self, method)
  380. except AttributeError:
  381. pass
  382. else:
  383. import warnings
  384. warnings.warn(f"{method} is deprecated; add visit_Constant",
  385. DeprecationWarning, 2)
  386. return visitor(node)
  387. return self.generic_visit(node)
  388. class NodeTransformer(NodeVisitor):
  389. """
  390. A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
  391. allows modification of nodes.
  392. The `NodeTransformer` will walk the AST and use the return value of the
  393. visitor methods to replace or remove the old node. If the return value of
  394. the visitor method is ``None``, the node will be removed from its location,
  395. otherwise it is replaced with the return value. The return value may be the
  396. original node in which case no replacement takes place.
  397. Here is an example transformer that rewrites all occurrences of name lookups
  398. (``foo``) to ``data['foo']``::
  399. class RewriteName(NodeTransformer):
  400. def visit_Name(self, node):
  401. return Subscript(
  402. value=Name(id='data', ctx=Load()),
  403. slice=Constant(value=node.id),
  404. ctx=node.ctx
  405. )
  406. Keep in mind that if the node you're operating on has child nodes you must
  407. either transform the child nodes yourself or call the :meth:`generic_visit`
  408. method for the node first.
  409. For nodes that were part of a collection of statements (that applies to all
  410. statement nodes), the visitor may also return a list of nodes rather than
  411. just a single node.
  412. Usually you use the transformer like this::
  413. node = YourTransformer().visit(node)
  414. """
  415. def generic_visit(self, node):
  416. for field, old_value in iter_fields(node):
  417. if isinstance(old_value, list):
  418. new_values = []
  419. for value in old_value:
  420. if isinstance(value, AST):
  421. value = self.visit(value)
  422. if value is None:
  423. continue
  424. elif not isinstance(value, AST):
  425. new_values.extend(value)
  426. continue
  427. new_values.append(value)
  428. old_value[:] = new_values
  429. elif isinstance(old_value, AST):
  430. new_node = self.visit(old_value)
  431. if new_node is None:
  432. delattr(node, field)
  433. else:
  434. setattr(node, field, new_node)
  435. return node
  436. _DEPRECATED_VALUE_ALIAS_MESSAGE = (
  437. "{name} is deprecated and will be removed in Python {remove}; use value instead"
  438. )
  439. _DEPRECATED_CLASS_MESSAGE = (
  440. "{name} is deprecated and will be removed in Python {remove}; "
  441. "use ast.Constant instead"
  442. )
  443. # If the ast module is loaded more than once, only add deprecated methods once
  444. if not hasattr(Constant, 'n'):
  445. # The following code is for backward compatibility.
  446. # It will be removed in future.
  447. def _n_getter(self):
  448. """Deprecated. Use value instead."""
  449. import warnings
  450. warnings._deprecated(
  451. "Attribute n", message=_DEPRECATED_VALUE_ALIAS_MESSAGE, remove=(3, 14)
  452. )
  453. return self.value
  454. def _n_setter(self, value):
  455. import warnings
  456. warnings._deprecated(
  457. "Attribute n", message=_DEPRECATED_VALUE_ALIAS_MESSAGE, remove=(3, 14)
  458. )
  459. self.value = value
  460. def _s_getter(self):
  461. """Deprecated. Use value instead."""
  462. import warnings
  463. warnings._deprecated(
  464. "Attribute s", message=_DEPRECATED_VALUE_ALIAS_MESSAGE, remove=(3, 14)
  465. )
  466. return self.value
  467. def _s_setter(self, value):
  468. import warnings
  469. warnings._deprecated(
  470. "Attribute s", message=_DEPRECATED_VALUE_ALIAS_MESSAGE, remove=(3, 14)
  471. )
  472. self.value = value
  473. Constant.n = property(_n_getter, _n_setter)
  474. Constant.s = property(_s_getter, _s_setter)
  475. class _ABC(type):
  476. def __init__(cls, *args):
  477. cls.__doc__ = """Deprecated AST node class. Use ast.Constant instead"""
  478. def __instancecheck__(cls, inst):
  479. if cls in _const_types:
  480. import warnings
  481. warnings._deprecated(
  482. f"ast.{cls.__qualname__}",
  483. message=_DEPRECATED_CLASS_MESSAGE,
  484. remove=(3, 14)
  485. )
  486. if not isinstance(inst, Constant):
  487. return False
  488. if cls in _const_types:
  489. try:
  490. value = inst.value
  491. except AttributeError:
  492. return False
  493. else:
  494. return (
  495. isinstance(value, _const_types[cls]) and
  496. not isinstance(value, _const_types_not.get(cls, ()))
  497. )
  498. return type.__instancecheck__(cls, inst)
  499. def _new(cls, *args, **kwargs):
  500. for key in kwargs:
  501. if key not in cls._fields:
  502. # arbitrary keyword arguments are accepted
  503. continue
  504. pos = cls._fields.index(key)
  505. if pos < len(args):
  506. raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}")
  507. if cls in _const_types:
  508. import warnings
  509. warnings._deprecated(
  510. f"ast.{cls.__qualname__}", message=_DEPRECATED_CLASS_MESSAGE, remove=(3, 14)
  511. )
  512. return Constant(*args, **kwargs)
  513. return Constant.__new__(cls, *args, **kwargs)
  514. class Num(Constant, metaclass=_ABC):
  515. _fields = ('n',)
  516. __new__ = _new
  517. class Str(Constant, metaclass=_ABC):
  518. _fields = ('s',)
  519. __new__ = _new
  520. class Bytes(Constant, metaclass=_ABC):
  521. _fields = ('s',)
  522. __new__ = _new
  523. class NameConstant(Constant, metaclass=_ABC):
  524. __new__ = _new
  525. class Ellipsis(Constant, metaclass=_ABC):
  526. _fields = ()
  527. def __new__(cls, *args, **kwargs):
  528. if cls is _ast_Ellipsis:
  529. import warnings
  530. warnings._deprecated(
  531. "ast.Ellipsis", message=_DEPRECATED_CLASS_MESSAGE, remove=(3, 14)
  532. )
  533. return Constant(..., *args, **kwargs)
  534. return Constant.__new__(cls, *args, **kwargs)
  535. # Keep another reference to Ellipsis in the global namespace
  536. # so it can be referenced in Ellipsis.__new__
  537. # (The original "Ellipsis" name is removed from the global namespace later on)
  538. _ast_Ellipsis = Ellipsis
  539. _const_types = {
  540. Num: (int, float, complex),
  541. Str: (str,),
  542. Bytes: (bytes,),
  543. NameConstant: (type(None), bool),
  544. Ellipsis: (type(...),),
  545. }
  546. _const_types_not = {
  547. Num: (bool,),
  548. }
  549. _const_node_type_names = {
  550. bool: 'NameConstant', # should be before int
  551. type(None): 'NameConstant',
  552. int: 'Num',
  553. float: 'Num',
  554. complex: 'Num',
  555. str: 'Str',
  556. bytes: 'Bytes',
  557. type(...): 'Ellipsis',
  558. }
  559. class slice(AST):
  560. """Deprecated AST node class."""
  561. class Index(slice):
  562. """Deprecated AST node class. Use the index value directly instead."""
  563. def __new__(cls, value, **kwargs):
  564. return value
  565. class ExtSlice(slice):
  566. """Deprecated AST node class. Use ast.Tuple instead."""
  567. def __new__(cls, dims=(), **kwargs):
  568. return Tuple(list(dims), Load(), **kwargs)
  569. # If the ast module is loaded more than once, only add deprecated methods once
  570. if not hasattr(Tuple, 'dims'):
  571. # The following code is for backward compatibility.
  572. # It will be removed in future.
  573. def _dims_getter(self):
  574. """Deprecated. Use elts instead."""
  575. return self.elts
  576. def _dims_setter(self, value):
  577. self.elts = value
  578. Tuple.dims = property(_dims_getter, _dims_setter)
  579. class Suite(mod):
  580. """Deprecated AST node class. Unused in Python 3."""
  581. class AugLoad(expr_context):
  582. """Deprecated AST node class. Unused in Python 3."""
  583. class AugStore(expr_context):
  584. """Deprecated AST node class. Unused in Python 3."""
  585. class Param(expr_context):
  586. """Deprecated AST node class. Unused in Python 3."""
  587. # Large float and imaginary literals get turned into infinities in the AST.
  588. # We unparse those infinities to INFSTR.
  589. _INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
  590. @_simple_enum(IntEnum)
  591. class _Precedence:
  592. """Precedence table that originated from python grammar."""
  593. NAMED_EXPR = auto() # <target> := <expr1>
  594. TUPLE = auto() # <expr1>, <expr2>
  595. YIELD = auto() # 'yield', 'yield from'
  596. TEST = auto() # 'if'-'else', 'lambda'
  597. OR = auto() # 'or'
  598. AND = auto() # 'and'
  599. NOT = auto() # 'not'
  600. CMP = auto() # '<', '>', '==', '>=', '<=', '!=',
  601. # 'in', 'not in', 'is', 'is not'
  602. EXPR = auto()
  603. BOR = EXPR # '|'
  604. BXOR = auto() # '^'
  605. BAND = auto() # '&'
  606. SHIFT = auto() # '<<', '>>'
  607. ARITH = auto() # '+', '-'
  608. TERM = auto() # '*', '@', '/', '%', '//'
  609. FACTOR = auto() # unary '+', '-', '~'
  610. POWER = auto() # '**'
  611. AWAIT = auto() # 'await'
  612. ATOM = auto()
  613. def next(self):
  614. try:
  615. return self.__class__(self + 1)
  616. except ValueError:
  617. return self
  618. _SINGLE_QUOTES = ("'", '"')
  619. _MULTI_QUOTES = ('"""', "'''")
  620. _ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)
  621. class _Unparser(NodeVisitor):
  622. """Methods in this class recursively traverse an AST and
  623. output source code for the abstract syntax; original formatting
  624. is disregarded."""
  625. def __init__(self, *, _avoid_backslashes=False):
  626. self._source = []
  627. self._precedences = {}
  628. self._type_ignores = {}
  629. self._indent = 0
  630. self._avoid_backslashes = _avoid_backslashes
  631. self._in_try_star = False
  632. def interleave(self, inter, f, seq):
  633. """Call f on each item in seq, calling inter() in between."""
  634. seq = iter(seq)
  635. try:
  636. f(next(seq))
  637. except StopIteration:
  638. pass
  639. else:
  640. for x in seq:
  641. inter()
  642. f(x)
  643. def items_view(self, traverser, items):
  644. """Traverse and separate the given *items* with a comma and append it to
  645. the buffer. If *items* is a single item sequence, a trailing comma
  646. will be added."""
  647. if len(items) == 1:
  648. traverser(items[0])
  649. self.write(",")
  650. else:
  651. self.interleave(lambda: self.write(", "), traverser, items)
  652. def maybe_newline(self):
  653. """Adds a newline if it isn't the start of generated source"""
  654. if self._source:
  655. self.write("\n")
  656. def fill(self, text=""):
  657. """Indent a piece of text and append it, according to the current
  658. indentation level"""
  659. self.maybe_newline()
  660. self.write(" " * self._indent + text)
  661. def write(self, *text):
  662. """Add new source parts"""
  663. self._source.extend(text)
  664. @contextmanager
  665. def buffered(self, buffer = None):
  666. if buffer is None:
  667. buffer = []
  668. original_source = self._source
  669. self._source = buffer
  670. yield buffer
  671. self._source = original_source
  672. @contextmanager
  673. def block(self, *, extra = None):
  674. """A context manager for preparing the source for blocks. It adds
  675. the character':', increases the indentation on enter and decreases
  676. the indentation on exit. If *extra* is given, it will be directly
  677. appended after the colon character.
  678. """
  679. self.write(":")
  680. if extra:
  681. self.write(extra)
  682. self._indent += 1
  683. yield
  684. self._indent -= 1
  685. @contextmanager
  686. def delimit(self, start, end):
  687. """A context manager for preparing the source for expressions. It adds
  688. *start* to the buffer and enters, after exit it adds *end*."""
  689. self.write(start)
  690. yield
  691. self.write(end)
  692. def delimit_if(self, start, end, condition):
  693. if condition:
  694. return self.delimit(start, end)
  695. else:
  696. return nullcontext()
  697. def require_parens(self, precedence, node):
  698. """Shortcut to adding precedence related parens"""
  699. return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
  700. def get_precedence(self, node):
  701. return self._precedences.get(node, _Precedence.TEST)
  702. def set_precedence(self, precedence, *nodes):
  703. for node in nodes:
  704. self._precedences[node] = precedence
  705. def get_raw_docstring(self, node):
  706. """If a docstring node is found in the body of the *node* parameter,
  707. return that docstring node, None otherwise.
  708. Logic mirrored from ``_PyAST_GetDocString``."""
  709. if not isinstance(
  710. node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)
  711. ) or len(node.body) < 1:
  712. return None
  713. node = node.body[0]
  714. if not isinstance(node, Expr):
  715. return None
  716. node = node.value
  717. if isinstance(node, Constant) and isinstance(node.value, str):
  718. return node
  719. def get_type_comment(self, node):
  720. comment = self._type_ignores.get(node.lineno) or node.type_comment
  721. if comment is not None:
  722. return f" # type: {comment}"
  723. def traverse(self, node):
  724. if isinstance(node, list):
  725. for item in node:
  726. self.traverse(item)
  727. else:
  728. super().visit(node)
  729. # Note: as visit() resets the output text, do NOT rely on
  730. # NodeVisitor.generic_visit to handle any nodes (as it calls back in to
  731. # the subclass visit() method, which resets self._source to an empty list)
  732. def visit(self, node):
  733. """Outputs a source code string that, if converted back to an ast
  734. (using ast.parse) will generate an AST equivalent to *node*"""
  735. self._source = []
  736. self.traverse(node)
  737. return "".join(self._source)
  738. def _write_docstring_and_traverse_body(self, node):
  739. if (docstring := self.get_raw_docstring(node)):
  740. self._write_docstring(docstring)
  741. self.traverse(node.body[1:])
  742. else:
  743. self.traverse(node.body)
  744. def visit_Module(self, node):
  745. self._type_ignores = {
  746. ignore.lineno: f"ignore{ignore.tag}"
  747. for ignore in node.type_ignores
  748. }
  749. self._write_docstring_and_traverse_body(node)
  750. self._type_ignores.clear()
  751. def visit_FunctionType(self, node):
  752. with self.delimit("(", ")"):
  753. self.interleave(
  754. lambda: self.write(", "), self.traverse, node.argtypes
  755. )
  756. self.write(" -> ")
  757. self.traverse(node.returns)
  758. def visit_Expr(self, node):
  759. self.fill()
  760. self.set_precedence(_Precedence.YIELD, node.value)
  761. self.traverse(node.value)
  762. def visit_NamedExpr(self, node):
  763. with self.require_parens(_Precedence.NAMED_EXPR, node):
  764. self.set_precedence(_Precedence.ATOM, node.target, node.value)
  765. self.traverse(node.target)
  766. self.write(" := ")
  767. self.traverse(node.value)
  768. def visit_Import(self, node):
  769. self.fill("import ")
  770. self.interleave(lambda: self.write(", "), self.traverse, node.names)
  771. def visit_ImportFrom(self, node):
  772. self.fill("from ")
  773. self.write("." * (node.level or 0))
  774. if node.module:
  775. self.write(node.module)
  776. self.write(" import ")
  777. self.interleave(lambda: self.write(", "), self.traverse, node.names)
  778. def visit_Assign(self, node):
  779. self.fill()
  780. for target in node.targets:
  781. self.set_precedence(_Precedence.TUPLE, target)
  782. self.traverse(target)
  783. self.write(" = ")
  784. self.traverse(node.value)
  785. if type_comment := self.get_type_comment(node):
  786. self.write(type_comment)
  787. def visit_AugAssign(self, node):
  788. self.fill()
  789. self.traverse(node.target)
  790. self.write(" " + self.binop[node.op.__class__.__name__] + "= ")
  791. self.traverse(node.value)
  792. def visit_AnnAssign(self, node):
  793. self.fill()
  794. with self.delimit_if("(", ")", not node.simple and isinstance(node.target, Name)):
  795. self.traverse(node.target)
  796. self.write(": ")
  797. self.traverse(node.annotation)
  798. if node.value:
  799. self.write(" = ")
  800. self.traverse(node.value)
  801. def visit_Return(self, node):
  802. self.fill("return")
  803. if node.value:
  804. self.write(" ")
  805. self.traverse(node.value)
  806. def visit_Pass(self, node):
  807. self.fill("pass")
  808. def visit_Break(self, node):
  809. self.fill("break")
  810. def visit_Continue(self, node):
  811. self.fill("continue")
  812. def visit_Delete(self, node):
  813. self.fill("del ")
  814. self.interleave(lambda: self.write(", "), self.traverse, node.targets)
  815. def visit_Assert(self, node):
  816. self.fill("assert ")
  817. self.traverse(node.test)
  818. if node.msg:
  819. self.write(", ")
  820. self.traverse(node.msg)
  821. def visit_Global(self, node):
  822. self.fill("global ")
  823. self.interleave(lambda: self.write(", "), self.write, node.names)
  824. def visit_Nonlocal(self, node):
  825. self.fill("nonlocal ")
  826. self.interleave(lambda: self.write(", "), self.write, node.names)
  827. def visit_Await(self, node):
  828. with self.require_parens(_Precedence.AWAIT, node):
  829. self.write("await")
  830. if node.value:
  831. self.write(" ")
  832. self.set_precedence(_Precedence.ATOM, node.value)
  833. self.traverse(node.value)
  834. def visit_Yield(self, node):
  835. with self.require_parens(_Precedence.YIELD, node):
  836. self.write("yield")
  837. if node.value:
  838. self.write(" ")
  839. self.set_precedence(_Precedence.ATOM, node.value)
  840. self.traverse(node.value)
  841. def visit_YieldFrom(self, node):
  842. with self.require_parens(_Precedence.YIELD, node):
  843. self.write("yield from ")
  844. if not node.value:
  845. raise ValueError("Node can't be used without a value attribute.")
  846. self.set_precedence(_Precedence.ATOM, node.value)
  847. self.traverse(node.value)
  848. def visit_Raise(self, node):
  849. self.fill("raise")
  850. if not node.exc:
  851. if node.cause:
  852. raise ValueError(f"Node can't use cause without an exception.")
  853. return
  854. self.write(" ")
  855. self.traverse(node.exc)
  856. if node.cause:
  857. self.write(" from ")
  858. self.traverse(node.cause)
  859. def do_visit_try(self, node):
  860. self.fill("try")
  861. with self.block():
  862. self.traverse(node.body)
  863. for ex in node.handlers:
  864. self.traverse(ex)
  865. if node.orelse:
  866. self.fill("else")
  867. with self.block():
  868. self.traverse(node.orelse)
  869. if node.finalbody:
  870. self.fill("finally")
  871. with self.block():
  872. self.traverse(node.finalbody)
  873. def visit_Try(self, node):
  874. prev_in_try_star = self._in_try_star
  875. try:
  876. self._in_try_star = False
  877. self.do_visit_try(node)
  878. finally:
  879. self._in_try_star = prev_in_try_star
  880. def visit_TryStar(self, node):
  881. prev_in_try_star = self._in_try_star
  882. try:
  883. self._in_try_star = True
  884. self.do_visit_try(node)
  885. finally:
  886. self._in_try_star = prev_in_try_star
  887. def visit_ExceptHandler(self, node):
  888. self.fill("except*" if self._in_try_star else "except")
  889. if node.type:
  890. self.write(" ")
  891. self.traverse(node.type)
  892. if node.name:
  893. self.write(" as ")
  894. self.write(node.name)
  895. with self.block():
  896. self.traverse(node.body)
  897. def visit_ClassDef(self, node):
  898. self.maybe_newline()
  899. for deco in node.decorator_list:
  900. self.fill("@")
  901. self.traverse(deco)
  902. self.fill("class " + node.name)
  903. if hasattr(node, "type_params"):
  904. self._type_params_helper(node.type_params)
  905. with self.delimit_if("(", ")", condition = node.bases or node.keywords):
  906. comma = False
  907. for e in node.bases:
  908. if comma:
  909. self.write(", ")
  910. else:
  911. comma = True
  912. self.traverse(e)
  913. for e in node.keywords:
  914. if comma:
  915. self.write(", ")
  916. else:
  917. comma = True
  918. self.traverse(e)
  919. with self.block():
  920. self._write_docstring_and_traverse_body(node)
  921. def visit_FunctionDef(self, node):
  922. self._function_helper(node, "def")
  923. def visit_AsyncFunctionDef(self, node):
  924. self._function_helper(node, "async def")
  925. def _function_helper(self, node, fill_suffix):
  926. self.maybe_newline()
  927. for deco in node.decorator_list:
  928. self.fill("@")
  929. self.traverse(deco)
  930. def_str = fill_suffix + " " + node.name
  931. self.fill(def_str)
  932. if hasattr(node, "type_params"):
  933. self._type_params_helper(node.type_params)
  934. with self.delimit("(", ")"):
  935. self.traverse(node.args)
  936. if node.returns:
  937. self.write(" -> ")
  938. self.traverse(node.returns)
  939. with self.block(extra=self.get_type_comment(node)):
  940. self._write_docstring_and_traverse_body(node)
  941. def _type_params_helper(self, type_params):
  942. if type_params is not None and len(type_params) > 0:
  943. with self.delimit("[", "]"):
  944. self.interleave(lambda: self.write(", "), self.traverse, type_params)
  945. def visit_TypeVar(self, node):
  946. self.write(node.name)
  947. if node.bound:
  948. self.write(": ")
  949. self.traverse(node.bound)
  950. def visit_TypeVarTuple(self, node):
  951. self.write("*" + node.name)
  952. def visit_ParamSpec(self, node):
  953. self.write("**" + node.name)
  954. def visit_TypeAlias(self, node):
  955. self.fill("type ")
  956. self.traverse(node.name)
  957. self._type_params_helper(node.type_params)
  958. self.write(" = ")
  959. self.traverse(node.value)
  960. def visit_For(self, node):
  961. self._for_helper("for ", node)
  962. def visit_AsyncFor(self, node):
  963. self._for_helper("async for ", node)
  964. def _for_helper(self, fill, node):
  965. self.fill(fill)
  966. self.set_precedence(_Precedence.TUPLE, node.target)
  967. self.traverse(node.target)
  968. self.write(" in ")
  969. self.traverse(node.iter)
  970. with self.block(extra=self.get_type_comment(node)):
  971. self.traverse(node.body)
  972. if node.orelse:
  973. self.fill("else")
  974. with self.block():
  975. self.traverse(node.orelse)
  976. def visit_If(self, node):
  977. self.fill("if ")
  978. self.traverse(node.test)
  979. with self.block():
  980. self.traverse(node.body)
  981. # collapse nested ifs into equivalent elifs.
  982. while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], If):
  983. node = node.orelse[0]
  984. self.fill("elif ")
  985. self.traverse(node.test)
  986. with self.block():
  987. self.traverse(node.body)
  988. # final else
  989. if node.orelse:
  990. self.fill("else")
  991. with self.block():
  992. self.traverse(node.orelse)
  993. def visit_While(self, node):
  994. self.fill("while ")
  995. self.traverse(node.test)
  996. with self.block():
  997. self.traverse(node.body)
  998. if node.orelse:
  999. self.fill("else")
  1000. with self.block():
  1001. self.traverse(node.orelse)
  1002. def visit_With(self, node):
  1003. self.fill("with ")
  1004. self.interleave(lambda: self.write(", "), self.traverse, node.items)
  1005. with self.block(extra=self.get_type_comment(node)):
  1006. self.traverse(node.body)
  1007. def visit_AsyncWith(self, node):
  1008. self.fill("async with ")
  1009. self.interleave(lambda: self.write(", "), self.traverse, node.items)
  1010. with self.block(extra=self.get_type_comment(node)):
  1011. self.traverse(node.body)
  1012. def _str_literal_helper(
  1013. self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False
  1014. ):
  1015. """Helper for writing string literals, minimizing escapes.
  1016. Returns the tuple (string literal to write, possible quote types).
  1017. """
  1018. def escape_char(c):
  1019. # \n and \t are non-printable, but we only escape them if
  1020. # escape_special_whitespace is True
  1021. if not escape_special_whitespace and c in "\n\t":
  1022. return c
  1023. # Always escape backslashes and other non-printable characters
  1024. if c == "\\" or not c.isprintable():
  1025. return c.encode("unicode_escape").decode("ascii")
  1026. return c
  1027. escaped_string = "".join(map(escape_char, string))
  1028. possible_quotes = quote_types
  1029. if "\n" in escaped_string:
  1030. possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES]
  1031. possible_quotes = [q for q in possible_quotes if q not in escaped_string]
  1032. if not possible_quotes:
  1033. # If there aren't any possible_quotes, fallback to using repr
  1034. # on the original string. Try to use a quote from quote_types,
  1035. # e.g., so that we use triple quotes for docstrings.
  1036. string = repr(string)
  1037. quote = next((q for q in quote_types if string[0] in q), string[0])
  1038. return string[1:-1], [quote]
  1039. if escaped_string:
  1040. # Sort so that we prefer '''"''' over """\""""
  1041. possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])
  1042. # If we're using triple quotes and we'd need to escape a final
  1043. # quote, escape it
  1044. if possible_quotes[0][0] == escaped_string[-1]:
  1045. assert len(possible_quotes[0]) == 3
  1046. escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1]
  1047. return escaped_string, possible_quotes
  1048. def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES):
  1049. """Write string literal value with a best effort attempt to avoid backslashes."""
  1050. string, quote_types = self._str_literal_helper(string, quote_types=quote_types)
  1051. quote_type = quote_types[0]
  1052. self.write(f"{quote_type}{string}{quote_type}")
  1053. def visit_JoinedStr(self, node):
  1054. self.write("f")
  1055. fstring_parts = []
  1056. for value in node.values:
  1057. with self.buffered() as buffer:
  1058. self._write_fstring_inner(value)
  1059. fstring_parts.append(
  1060. ("".join(buffer), isinstance(value, Constant))
  1061. )
  1062. new_fstring_parts = []
  1063. quote_types = list(_ALL_QUOTES)
  1064. fallback_to_repr = False
  1065. for value, is_constant in fstring_parts:
  1066. if is_constant:
  1067. value, new_quote_types = self._str_literal_helper(
  1068. value,
  1069. quote_types=quote_types,
  1070. escape_special_whitespace=True,
  1071. )
  1072. if set(new_quote_types).isdisjoint(quote_types):
  1073. fallback_to_repr = True
  1074. break
  1075. quote_types = new_quote_types
  1076. elif "\n" in value:
  1077. quote_types = [q for q in quote_types if q in _MULTI_QUOTES]
  1078. assert quote_types
  1079. new_fstring_parts.append(value)
  1080. if fallback_to_repr:
  1081. # If we weren't able to find a quote type that works for all parts
  1082. # of the JoinedStr, fallback to using repr and triple single quotes.
  1083. quote_types = ["'''"]
  1084. new_fstring_parts.clear()
  1085. for value, is_constant in fstring_parts:
  1086. if is_constant:
  1087. value = repr('"' + value) # force repr to use single quotes
  1088. expected_prefix = "'\""
  1089. assert value.startswith(expected_prefix), repr(value)
  1090. value = value[len(expected_prefix):-1]
  1091. new_fstring_parts.append(value)
  1092. value = "".join(new_fstring_parts)
  1093. quote_type = quote_types[0]
  1094. self.write(f"{quote_type}{value}{quote_type}")
  1095. def _write_fstring_inner(self, node, is_format_spec=False):
  1096. if isinstance(node, JoinedStr):
  1097. # for both the f-string itself, and format_spec
  1098. for value in node.values:
  1099. self._write_fstring_inner(value, is_format_spec=is_format_spec)
  1100. elif isinstance(node, Constant) and isinstance(node.value, str):
  1101. value = node.value.replace("{", "{{").replace("}", "}}")
  1102. if is_format_spec:
  1103. value = value.replace("\\", "\\\\")
  1104. value = value.replace("'", "\\'")
  1105. value = value.replace('"', '\\"')
  1106. value = value.replace("\n", "\\n")
  1107. self.write(value)
  1108. elif isinstance(node, FormattedValue):
  1109. self.visit_FormattedValue(node)
  1110. else:
  1111. raise ValueError(f"Unexpected node inside JoinedStr, {node!r}")
  1112. def visit_FormattedValue(self, node):
  1113. def unparse_inner(inner):
  1114. unparser = type(self)()
  1115. unparser.set_precedence(_Precedence.TEST.next(), inner)
  1116. return unparser.visit(inner)
  1117. with self.delimit("{", "}"):
  1118. expr = unparse_inner(node.value)
  1119. if expr.startswith("{"):
  1120. # Separate pair of opening brackets as "{ {"
  1121. self.write(" ")
  1122. self.write(expr)
  1123. if node.conversion != -1:
  1124. self.write(f"!{chr(node.conversion)}")
  1125. if node.format_spec:
  1126. self.write(":")
  1127. self._write_fstring_inner(node.format_spec, is_format_spec=True)
  1128. def visit_Name(self, node):
  1129. self.write(node.id)
  1130. def _write_docstring(self, node):
  1131. self.fill()
  1132. if node.kind == "u":
  1133. self.write("u")
  1134. self._write_str_avoiding_backslashes(node.value, quote_types=_MULTI_QUOTES)
  1135. def _write_constant(self, value):
  1136. if isinstance(value, (float, complex)):
  1137. # Substitute overflowing decimal literal for AST infinities,
  1138. # and inf - inf for NaNs.
  1139. self.write(
  1140. repr(value)
  1141. .replace("inf", _INFSTR)
  1142. .replace("nan", f"({_INFSTR}-{_INFSTR})")
  1143. )
  1144. elif self._avoid_backslashes and isinstance(value, str):
  1145. self._write_str_avoiding_backslashes(value)
  1146. else:
  1147. self.write(repr(value))
  1148. def visit_Constant(self, node):
  1149. value = node.value
  1150. if isinstance(value, tuple):
  1151. with self.delimit("(", ")"):
  1152. self.items_view(self._write_constant, value)
  1153. elif value is ...:
  1154. self.write("...")
  1155. else:
  1156. if node.kind == "u":
  1157. self.write("u")
  1158. self._write_constant(node.value)
  1159. def visit_List(self, node):
  1160. with self.delimit("[", "]"):
  1161. self.interleave(lambda: self.write(", "), self.traverse, node.elts)
  1162. def visit_ListComp(self, node):
  1163. with self.delimit("[", "]"):
  1164. self.traverse(node.elt)
  1165. for gen in node.generators:
  1166. self.traverse(gen)
  1167. def visit_GeneratorExp(self, node):
  1168. with self.delimit("(", ")"):
  1169. self.traverse(node.elt)
  1170. for gen in node.generators:
  1171. self.traverse(gen)
  1172. def visit_SetComp(self, node):
  1173. with self.delimit("{", "}"):
  1174. self.traverse(node.elt)
  1175. for gen in node.generators:
  1176. self.traverse(gen)
  1177. def visit_DictComp(self, node):
  1178. with self.delimit("{", "}"):
  1179. self.traverse(node.key)
  1180. self.write(": ")
  1181. self.traverse(node.value)
  1182. for gen in node.generators:
  1183. self.traverse(gen)
  1184. def visit_comprehension(self, node):
  1185. if node.is_async:
  1186. self.write(" async for ")
  1187. else:
  1188. self.write(" for ")
  1189. self.set_precedence(_Precedence.TUPLE, node.target)
  1190. self.traverse(node.target)
  1191. self.write(" in ")
  1192. self.set_precedence(_Precedence.TEST.next(), node.iter, *node.ifs)
  1193. self.traverse(node.iter)
  1194. for if_clause in node.ifs:
  1195. self.write(" if ")
  1196. self.traverse(if_clause)
  1197. def visit_IfExp(self, node):
  1198. with self.require_parens(_Precedence.TEST, node):
  1199. self.set_precedence(_Precedence.TEST.next(), node.body, node.test)
  1200. self.traverse(node.body)
  1201. self.write(" if ")
  1202. self.traverse(node.test)
  1203. self.write(" else ")
  1204. self.set_precedence(_Precedence.TEST, node.orelse)
  1205. self.traverse(node.orelse)
  1206. def visit_Set(self, node):
  1207. if node.elts:
  1208. with self.delimit("{", "}"):
  1209. self.interleave(lambda: self.write(", "), self.traverse, node.elts)
  1210. else:
  1211. # `{}` would be interpreted as a dictionary literal, and
  1212. # `set` might be shadowed. Thus:
  1213. self.write('{*()}')
  1214. def visit_Dict(self, node):
  1215. def write_key_value_pair(k, v):
  1216. self.traverse(k)
  1217. self.write(": ")
  1218. self.traverse(v)
  1219. def write_item(item):
  1220. k, v = item
  1221. if k is None:
  1222. # for dictionary unpacking operator in dicts {**{'y': 2}}
  1223. # see PEP 448 for details
  1224. self.write("**")
  1225. self.set_precedence(_Precedence.EXPR, v)
  1226. self.traverse(v)
  1227. else:
  1228. write_key_value_pair(k, v)
  1229. with self.delimit("{", "}"):
  1230. self.interleave(
  1231. lambda: self.write(", "), write_item, zip(node.keys, node.values)
  1232. )
  1233. def visit_Tuple(self, node):
  1234. with self.delimit_if(
  1235. "(",
  1236. ")",
  1237. len(node.elts) == 0 or self.get_precedence(node) > _Precedence.TUPLE
  1238. ):
  1239. self.items_view(self.traverse, node.elts)
  1240. unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"}
  1241. unop_precedence = {
  1242. "not": _Precedence.NOT,
  1243. "~": _Precedence.FACTOR,
  1244. "+": _Precedence.FACTOR,
  1245. "-": _Precedence.FACTOR,
  1246. }
  1247. def visit_UnaryOp(self, node):
  1248. operator = self.unop[node.op.__class__.__name__]
  1249. operator_precedence = self.unop_precedence[operator]
  1250. with self.require_parens(operator_precedence, node):
  1251. self.write(operator)
  1252. # factor prefixes (+, -, ~) shouldn't be separated
  1253. # from the value they belong, (e.g: +1 instead of + 1)
  1254. if operator_precedence is not _Precedence.FACTOR:
  1255. self.write(" ")
  1256. self.set_precedence(operator_precedence, node.operand)
  1257. self.traverse(node.operand)
  1258. binop = {
  1259. "Add": "+",
  1260. "Sub": "-",
  1261. "Mult": "*",
  1262. "MatMult": "@",
  1263. "Div": "/",
  1264. "Mod": "%",
  1265. "LShift": "<<",
  1266. "RShift": ">>",
  1267. "BitOr": "|",
  1268. "BitXor": "^",
  1269. "BitAnd": "&",
  1270. "FloorDiv": "//",
  1271. "Pow": "**",
  1272. }
  1273. binop_precedence = {
  1274. "+": _Precedence.ARITH,
  1275. "-": _Precedence.ARITH,
  1276. "*": _Precedence.TERM,
  1277. "@": _Precedence.TERM,
  1278. "/": _Precedence.TERM,
  1279. "%": _Precedence.TERM,
  1280. "<<": _Precedence.SHIFT,
  1281. ">>": _Precedence.SHIFT,
  1282. "|": _Precedence.BOR,
  1283. "^": _Precedence.BXOR,
  1284. "&": _Precedence.BAND,
  1285. "//": _Precedence.TERM,
  1286. "**": _Precedence.POWER,
  1287. }
  1288. binop_rassoc = frozenset(("**",))
  1289. def visit_BinOp(self, node):
  1290. operator = self.binop[node.op.__class__.__name__]
  1291. operator_precedence = self.binop_precedence[operator]
  1292. with self.require_parens(operator_precedence, node):
  1293. if operator in self.binop_rassoc:
  1294. left_precedence = operator_precedence.next()
  1295. right_precedence = operator_precedence
  1296. else:
  1297. left_precedence = operator_precedence
  1298. right_precedence = operator_precedence.next()
  1299. self.set_precedence(left_precedence, node.left)
  1300. self.traverse(node.left)
  1301. self.write(f" {operator} ")
  1302. self.set_precedence(right_precedence, node.right)
  1303. self.traverse(node.right)
  1304. cmpops = {
  1305. "Eq": "==",
  1306. "NotEq": "!=",
  1307. "Lt": "<",
  1308. "LtE": "<=",
  1309. "Gt": ">",
  1310. "GtE": ">=",
  1311. "Is": "is",
  1312. "IsNot": "is not",
  1313. "In": "in",
  1314. "NotIn": "not in",
  1315. }
  1316. def visit_Compare(self, node):
  1317. with self.require_parens(_Precedence.CMP, node):
  1318. self.set_precedence(_Precedence.CMP.next(), node.left, *node.comparators)
  1319. self.traverse(node.left)
  1320. for o, e in zip(node.ops, node.comparators):
  1321. self.write(" " + self.cmpops[o.__class__.__name__] + " ")
  1322. self.traverse(e)
  1323. boolops = {"And": "and", "Or": "or"}
  1324. boolop_precedence = {"and": _Precedence.AND, "or": _Precedence.OR}
  1325. def visit_BoolOp(self, node):
  1326. operator = self.boolops[node.op.__class__.__name__]
  1327. operator_precedence = self.boolop_precedence[operator]
  1328. def increasing_level_traverse(node):
  1329. nonlocal operator_precedence
  1330. operator_precedence = operator_precedence.next()
  1331. self.set_precedence(operator_precedence, node)
  1332. self.traverse(node)
  1333. with self.require_parens(operator_precedence, node):
  1334. s = f" {operator} "
  1335. self.interleave(lambda: self.write(s), increasing_level_traverse, node.values)
  1336. def visit_Attribute(self, node):
  1337. self.set_precedence(_Precedence.ATOM, node.value)
  1338. self.traverse(node.value)
  1339. # Special case: 3.__abs__() is a syntax error, so if node.value
  1340. # is an integer literal then we need to either parenthesize
  1341. # it or add an extra space to get 3 .__abs__().
  1342. if isinstance(node.value, Constant) and isinstance(node.value.value, int):
  1343. self.write(" ")
  1344. self.write(".")
  1345. self.write(node.attr)
  1346. def visit_Call(self, node):
  1347. self.set_precedence(_Precedence.ATOM, node.func)
  1348. self.traverse(node.func)
  1349. with self.delimit("(", ")"):
  1350. comma = False
  1351. for e in node.args:
  1352. if comma:
  1353. self.write(", ")
  1354. else:
  1355. comma = True
  1356. self.traverse(e)
  1357. for e in node.keywords:
  1358. if comma:
  1359. self.write(", ")
  1360. else:
  1361. comma = True
  1362. self.traverse(e)
  1363. def visit_Subscript(self, node):
  1364. def is_non_empty_tuple(slice_value):
  1365. return (
  1366. isinstance(slice_value, Tuple)
  1367. and slice_value.elts
  1368. )
  1369. self.set_precedence(_Precedence.ATOM, node.value)
  1370. self.traverse(node.value)
  1371. with self.delimit("[", "]"):
  1372. if is_non_empty_tuple(node.slice):
  1373. # parentheses can be omitted if the tuple isn't empty
  1374. self.items_view(self.traverse, node.slice.elts)
  1375. else:
  1376. self.traverse(node.slice)
  1377. def visit_Starred(self, node):
  1378. self.write("*")
  1379. self.set_precedence(_Precedence.EXPR, node.value)
  1380. self.traverse(node.value)
  1381. def visit_Ellipsis(self, node):
  1382. self.write("...")
  1383. def visit_Slice(self, node):
  1384. if node.lower:
  1385. self.traverse(node.lower)
  1386. self.write(":")
  1387. if node.upper:
  1388. self.traverse(node.upper)
  1389. if node.step:
  1390. self.write(":")
  1391. self.traverse(node.step)
  1392. def visit_Match(self, node):
  1393. self.fill("match ")
  1394. self.traverse(node.subject)
  1395. with self.block():
  1396. for case in node.cases:
  1397. self.traverse(case)
  1398. def visit_arg(self, node):
  1399. self.write(node.arg)
  1400. if node.annotation:
  1401. self.write(": ")
  1402. self.traverse(node.annotation)
  1403. def visit_arguments(self, node):
  1404. first = True
  1405. # normal arguments
  1406. all_args = node.posonlyargs + node.args
  1407. defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults
  1408. for index, elements in enumerate(zip(all_args, defaults), 1):
  1409. a, d = elements
  1410. if first:
  1411. first = False
  1412. else:
  1413. self.write(", ")
  1414. self.traverse(a)
  1415. if d:
  1416. self.write("=")
  1417. self.traverse(d)
  1418. if index == len(node.posonlyargs):
  1419. self.write(", /")
  1420. # varargs, or bare '*' if no varargs but keyword-only arguments present
  1421. if node.vararg or node.kwonlyargs:
  1422. if first:
  1423. first = False
  1424. else:
  1425. self.write(", ")
  1426. self.write("*")
  1427. if node.vararg:
  1428. self.write(node.vararg.arg)
  1429. if node.vararg.annotation:
  1430. self.write(": ")
  1431. self.traverse(node.vararg.annotation)
  1432. # keyword-only arguments
  1433. if node.kwonlyargs:
  1434. for a, d in zip(node.kwonlyargs, node.kw_defaults):
  1435. self.write(", ")
  1436. self.traverse(a)
  1437. if d:
  1438. self.write("=")
  1439. self.traverse(d)
  1440. # kwargs
  1441. if node.kwarg:
  1442. if first:
  1443. first = False
  1444. else:
  1445. self.write(", ")
  1446. self.write("**" + node.kwarg.arg)
  1447. if node.kwarg.annotation:
  1448. self.write(": ")
  1449. self.traverse(node.kwarg.annotation)
  1450. def visit_keyword(self, node):
  1451. if node.arg is None:
  1452. self.write("**")
  1453. else:
  1454. self.write(node.arg)
  1455. self.write("=")
  1456. self.traverse(node.value)
  1457. def visit_Lambda(self, node):
  1458. with self.require_parens(_Precedence.TEST, node):
  1459. self.write("lambda")
  1460. with self.buffered() as buffer:
  1461. self.traverse(node.args)
  1462. if buffer:
  1463. self.write(" ", *buffer)
  1464. self.write(": ")
  1465. self.set_precedence(_Precedence.TEST, node.body)
  1466. self.traverse(node.body)
  1467. def visit_alias(self, node):
  1468. self.write(node.name)
  1469. if node.asname:
  1470. self.write(" as " + node.asname)
  1471. def visit_withitem(self, node):
  1472. self.traverse(node.context_expr)
  1473. if node.optional_vars:
  1474. self.write(" as ")
  1475. self.traverse(node.optional_vars)
  1476. def visit_match_case(self, node):
  1477. self.fill("case ")
  1478. self.traverse(node.pattern)
  1479. if node.guard:
  1480. self.write(" if ")
  1481. self.traverse(node.guard)
  1482. with self.block():
  1483. self.traverse(node.body)
  1484. def visit_MatchValue(self, node):
  1485. self.traverse(node.value)
  1486. def visit_MatchSingleton(self, node):
  1487. self._write_constant(node.value)
  1488. def visit_MatchSequence(self, node):
  1489. with self.delimit("[", "]"):
  1490. self.interleave(
  1491. lambda: self.write(", "), self.traverse, node.patterns
  1492. )
  1493. def visit_MatchStar(self, node):
  1494. name = node.name
  1495. if name is None:
  1496. name = "_"
  1497. self.write(f"*{name}")
  1498. def visit_MatchMapping(self, node):
  1499. def write_key_pattern_pair(pair):
  1500. k, p = pair
  1501. self.traverse(k)
  1502. self.write(": ")
  1503. self.traverse(p)
  1504. with self.delimit("{", "}"):
  1505. keys = node.keys
  1506. self.interleave(
  1507. lambda: self.write(", "),
  1508. write_key_pattern_pair,
  1509. zip(keys, node.patterns, strict=True),
  1510. )
  1511. rest = node.rest
  1512. if rest is not None:
  1513. if keys:
  1514. self.write(", ")
  1515. self.write(f"**{rest}")
  1516. def visit_MatchClass(self, node):
  1517. self.set_precedence(_Precedence.ATOM, node.cls)
  1518. self.traverse(node.cls)
  1519. with self.delimit("(", ")"):
  1520. patterns = node.patterns
  1521. self.interleave(
  1522. lambda: self.write(", "), self.traverse, patterns
  1523. )
  1524. attrs = node.kwd_attrs
  1525. if attrs:
  1526. def write_attr_pattern(pair):
  1527. attr, pattern = pair
  1528. self.write(f"{attr}=")
  1529. self.traverse(pattern)
  1530. if patterns:
  1531. self.write(", ")
  1532. self.interleave(
  1533. lambda: self.write(", "),
  1534. write_attr_pattern,
  1535. zip(attrs, node.kwd_patterns, strict=True),
  1536. )
  1537. def visit_MatchAs(self, node):
  1538. name = node.name
  1539. pattern = node.pattern
  1540. if name is None:
  1541. self.write("_")
  1542. elif pattern is None:
  1543. self.write(node.name)
  1544. else:
  1545. with self.require_parens(_Precedence.TEST, node):
  1546. self.set_precedence(_Precedence.BOR, node.pattern)
  1547. self.traverse(node.pattern)
  1548. self.write(f" as {node.name}")
  1549. def visit_MatchOr(self, node):
  1550. with self.require_parens(_Precedence.BOR, node):
  1551. self.set_precedence(_Precedence.BOR.next(), *node.patterns)
  1552. self.interleave(lambda: self.write(" | "), self.traverse, node.patterns)
  1553. def unparse(ast_obj):
  1554. unparser = _Unparser()
  1555. return unparser.visit(ast_obj)
  1556. _deprecated_globals = {
  1557. name: globals().pop(name)
  1558. for name in ('Num', 'Str', 'Bytes', 'NameConstant', 'Ellipsis')
  1559. }
  1560. def __getattr__(name):
  1561. if name in _deprecated_globals:
  1562. globals()[name] = value = _deprecated_globals[name]
  1563. import warnings
  1564. warnings._deprecated(
  1565. f"ast.{name}", message=_DEPRECATED_CLASS_MESSAGE, remove=(3, 14)
  1566. )
  1567. return value
  1568. raise AttributeError(f"module 'ast' has no attribute '{name}'")
  1569. def main():
  1570. import argparse
  1571. parser = argparse.ArgumentParser(prog='python -m ast')
  1572. parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?',
  1573. default='-',
  1574. help='the file to parse; defaults to stdin')
  1575. parser.add_argument('-m', '--mode', default='exec',
  1576. choices=('exec', 'single', 'eval', 'func_type'),
  1577. help='specify what kind of code must be parsed')
  1578. parser.add_argument('--no-type-comments', default=True, action='store_false',
  1579. help="don't add information about type comments")
  1580. parser.add_argument('-a', '--include-attributes', action='store_true',
  1581. help='include attributes such as line numbers and '
  1582. 'column offsets')
  1583. parser.add_argument('-i', '--indent', type=int, default=3,
  1584. help='indentation of nodes (number of spaces)')
  1585. args = parser.parse_args()
  1586. with args.infile as infile:
  1587. source = infile.read()
  1588. tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments)
  1589. print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))
  1590. if __name__ == '__main__':
  1591. main()