ast.py 55 KB

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