Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ExeBy/smexe_ro.../usr/lib64/python3....
File: ast.py
"""
[0] Fix | Delete
ast
[1] Fix | Delete
~~~
[2] Fix | Delete
[3] Fix | Delete
The `ast` module helps Python applications to process trees of the Python
[4] Fix | Delete
abstract syntax grammar. The abstract syntax itself might change with
[5] Fix | Delete
each Python release; this module helps to find out programmatically what
[6] Fix | Delete
the current grammar looks like and allows modifications of it.
[7] Fix | Delete
[8] Fix | Delete
An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
[9] Fix | Delete
a flag to the `compile()` builtin function or by using the `parse()`
[10] Fix | Delete
function from this module. The result will be a tree of objects whose
[11] Fix | Delete
classes all inherit from `ast.AST`.
[12] Fix | Delete
[13] Fix | Delete
A modified abstract syntax tree can be compiled into a Python code object
[14] Fix | Delete
using the built-in `compile()` function.
[15] Fix | Delete
[16] Fix | Delete
Additionally various helper functions are provided that make working with
[17] Fix | Delete
the trees simpler. The main intention of the helper functions and this
[18] Fix | Delete
module in general is to provide an easy to use interface for libraries
[19] Fix | Delete
that work tightly with the python syntax (template engines for example).
[20] Fix | Delete
[21] Fix | Delete
[22] Fix | Delete
:copyright: Copyright 2008 by Armin Ronacher.
[23] Fix | Delete
:license: Python License.
[24] Fix | Delete
"""
[25] Fix | Delete
from _ast import *
[26] Fix | Delete
[27] Fix | Delete
[28] Fix | Delete
def parse(source, filename='<unknown>', mode='exec'):
[29] Fix | Delete
"""
[30] Fix | Delete
Parse the source into an AST node.
[31] Fix | Delete
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
[32] Fix | Delete
"""
[33] Fix | Delete
return compile(source, filename, mode, PyCF_ONLY_AST)
[34] Fix | Delete
[35] Fix | Delete
[36] Fix | Delete
_NUM_TYPES = (int, float, complex)
[37] Fix | Delete
[38] Fix | Delete
def literal_eval(node_or_string):
[39] Fix | Delete
"""
[40] Fix | Delete
Safely evaluate an expression node or a string containing a Python
[41] Fix | Delete
expression. The string or node provided may only consist of the following
[42] Fix | Delete
Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
[43] Fix | Delete
sets, booleans, and None.
[44] Fix | Delete
"""
[45] Fix | Delete
if isinstance(node_or_string, str):
[46] Fix | Delete
node_or_string = parse(node_or_string, mode='eval')
[47] Fix | Delete
if isinstance(node_or_string, Expression):
[48] Fix | Delete
node_or_string = node_or_string.body
[49] Fix | Delete
def _convert(node):
[50] Fix | Delete
if isinstance(node, Constant):
[51] Fix | Delete
return node.value
[52] Fix | Delete
elif isinstance(node, (Str, Bytes)):
[53] Fix | Delete
return node.s
[54] Fix | Delete
elif isinstance(node, Num):
[55] Fix | Delete
return node.n
[56] Fix | Delete
elif isinstance(node, Tuple):
[57] Fix | Delete
return tuple(map(_convert, node.elts))
[58] Fix | Delete
elif isinstance(node, List):
[59] Fix | Delete
return list(map(_convert, node.elts))
[60] Fix | Delete
elif isinstance(node, Set):
[61] Fix | Delete
return set(map(_convert, node.elts))
[62] Fix | Delete
elif isinstance(node, Dict):
[63] Fix | Delete
return dict((_convert(k), _convert(v)) for k, v
[64] Fix | Delete
in zip(node.keys, node.values))
[65] Fix | Delete
elif isinstance(node, NameConstant):
[66] Fix | Delete
return node.value
[67] Fix | Delete
elif isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
[68] Fix | Delete
operand = _convert(node.operand)
[69] Fix | Delete
if isinstance(operand, _NUM_TYPES):
[70] Fix | Delete
if isinstance(node.op, UAdd):
[71] Fix | Delete
return + operand
[72] Fix | Delete
else:
[73] Fix | Delete
return - operand
[74] Fix | Delete
elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
[75] Fix | Delete
left = _convert(node.left)
[76] Fix | Delete
right = _convert(node.right)
[77] Fix | Delete
if isinstance(left, _NUM_TYPES) and isinstance(right, _NUM_TYPES):
[78] Fix | Delete
if isinstance(node.op, Add):
[79] Fix | Delete
return left + right
[80] Fix | Delete
else:
[81] Fix | Delete
return left - right
[82] Fix | Delete
raise ValueError('malformed node or string: ' + repr(node))
[83] Fix | Delete
return _convert(node_or_string)
[84] Fix | Delete
[85] Fix | Delete
[86] Fix | Delete
def dump(node, annotate_fields=True, include_attributes=False):
[87] Fix | Delete
"""
[88] Fix | Delete
Return a formatted dump of the tree in *node*. This is mainly useful for
[89] Fix | Delete
debugging purposes. The returned string will show the names and the values
[90] Fix | Delete
for fields. This makes the code impossible to evaluate, so if evaluation is
[91] Fix | Delete
wanted *annotate_fields* must be set to False. Attributes such as line
[92] Fix | Delete
numbers and column offsets are not dumped by default. If this is wanted,
[93] Fix | Delete
*include_attributes* can be set to True.
[94] Fix | Delete
"""
[95] Fix | Delete
def _format(node):
[96] Fix | Delete
if isinstance(node, AST):
[97] Fix | Delete
fields = [(a, _format(b)) for a, b in iter_fields(node)]
[98] Fix | Delete
rv = '%s(%s' % (node.__class__.__name__, ', '.join(
[99] Fix | Delete
('%s=%s' % field for field in fields)
[100] Fix | Delete
if annotate_fields else
[101] Fix | Delete
(b for a, b in fields)
[102] Fix | Delete
))
[103] Fix | Delete
if include_attributes and node._attributes:
[104] Fix | Delete
rv += fields and ', ' or ' '
[105] Fix | Delete
rv += ', '.join('%s=%s' % (a, _format(getattr(node, a)))
[106] Fix | Delete
for a in node._attributes)
[107] Fix | Delete
return rv + ')'
[108] Fix | Delete
elif isinstance(node, list):
[109] Fix | Delete
return '[%s]' % ', '.join(_format(x) for x in node)
[110] Fix | Delete
return repr(node)
[111] Fix | Delete
if not isinstance(node, AST):
[112] Fix | Delete
raise TypeError('expected AST, got %r' % node.__class__.__name__)
[113] Fix | Delete
return _format(node)
[114] Fix | Delete
[115] Fix | Delete
[116] Fix | Delete
def copy_location(new_node, old_node):
[117] Fix | Delete
"""
[118] Fix | Delete
Copy source location (`lineno` and `col_offset` attributes) from
[119] Fix | Delete
*old_node* to *new_node* if possible, and return *new_node*.
[120] Fix | Delete
"""
[121] Fix | Delete
for attr in 'lineno', 'col_offset':
[122] Fix | Delete
if attr in old_node._attributes and attr in new_node._attributes \
[123] Fix | Delete
and hasattr(old_node, attr):
[124] Fix | Delete
setattr(new_node, attr, getattr(old_node, attr))
[125] Fix | Delete
return new_node
[126] Fix | Delete
[127] Fix | Delete
[128] Fix | Delete
def fix_missing_locations(node):
[129] Fix | Delete
"""
[130] Fix | Delete
When you compile a node tree with compile(), the compiler expects lineno and
[131] Fix | Delete
col_offset attributes for every node that supports them. This is rather
[132] Fix | Delete
tedious to fill in for generated nodes, so this helper adds these attributes
[133] Fix | Delete
recursively where not already set, by setting them to the values of the
[134] Fix | Delete
parent node. It works recursively starting at *node*.
[135] Fix | Delete
"""
[136] Fix | Delete
def _fix(node, lineno, col_offset):
[137] Fix | Delete
if 'lineno' in node._attributes:
[138] Fix | Delete
if not hasattr(node, 'lineno'):
[139] Fix | Delete
node.lineno = lineno
[140] Fix | Delete
else:
[141] Fix | Delete
lineno = node.lineno
[142] Fix | Delete
if 'col_offset' in node._attributes:
[143] Fix | Delete
if not hasattr(node, 'col_offset'):
[144] Fix | Delete
node.col_offset = col_offset
[145] Fix | Delete
else:
[146] Fix | Delete
col_offset = node.col_offset
[147] Fix | Delete
for child in iter_child_nodes(node):
[148] Fix | Delete
_fix(child, lineno, col_offset)
[149] Fix | Delete
_fix(node, 1, 0)
[150] Fix | Delete
return node
[151] Fix | Delete
[152] Fix | Delete
[153] Fix | Delete
def increment_lineno(node, n=1):
[154] Fix | Delete
"""
[155] Fix | Delete
Increment the line number of each node in the tree starting at *node* by *n*.
[156] Fix | Delete
This is useful to "move code" to a different location in a file.
[157] Fix | Delete
"""
[158] Fix | Delete
for child in walk(node):
[159] Fix | Delete
if 'lineno' in child._attributes:
[160] Fix | Delete
child.lineno = getattr(child, 'lineno', 0) + n
[161] Fix | Delete
return node
[162] Fix | Delete
[163] Fix | Delete
[164] Fix | Delete
def iter_fields(node):
[165] Fix | Delete
"""
[166] Fix | Delete
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
[167] Fix | Delete
that is present on *node*.
[168] Fix | Delete
"""
[169] Fix | Delete
for field in node._fields:
[170] Fix | Delete
try:
[171] Fix | Delete
yield field, getattr(node, field)
[172] Fix | Delete
except AttributeError:
[173] Fix | Delete
pass
[174] Fix | Delete
[175] Fix | Delete
[176] Fix | Delete
def iter_child_nodes(node):
[177] Fix | Delete
"""
[178] Fix | Delete
Yield all direct child nodes of *node*, that is, all fields that are nodes
[179] Fix | Delete
and all items of fields that are lists of nodes.
[180] Fix | Delete
"""
[181] Fix | Delete
for name, field in iter_fields(node):
[182] Fix | Delete
if isinstance(field, AST):
[183] Fix | Delete
yield field
[184] Fix | Delete
elif isinstance(field, list):
[185] Fix | Delete
for item in field:
[186] Fix | Delete
if isinstance(item, AST):
[187] Fix | Delete
yield item
[188] Fix | Delete
[189] Fix | Delete
[190] Fix | Delete
def get_docstring(node, clean=True):
[191] Fix | Delete
"""
[192] Fix | Delete
Return the docstring for the given node or None if no docstring can
[193] Fix | Delete
be found. If the node provided does not have docstrings a TypeError
[194] Fix | Delete
will be raised.
[195] Fix | Delete
"""
[196] Fix | Delete
if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
[197] Fix | Delete
raise TypeError("%r can't have docstrings" % node.__class__.__name__)
[198] Fix | Delete
if not(node.body and isinstance(node.body[0], Expr)):
[199] Fix | Delete
return
[200] Fix | Delete
node = node.body[0].value
[201] Fix | Delete
if isinstance(node, Str):
[202] Fix | Delete
text = node.s
[203] Fix | Delete
elif isinstance(node, Constant) and isinstance(node.value, str):
[204] Fix | Delete
text = node.value
[205] Fix | Delete
else:
[206] Fix | Delete
return
[207] Fix | Delete
if clean:
[208] Fix | Delete
import inspect
[209] Fix | Delete
text = inspect.cleandoc(text)
[210] Fix | Delete
return text
[211] Fix | Delete
[212] Fix | Delete
[213] Fix | Delete
def walk(node):
[214] Fix | Delete
"""
[215] Fix | Delete
Recursively yield all descendant nodes in the tree starting at *node*
[216] Fix | Delete
(including *node* itself), in no specified order. This is useful if you
[217] Fix | Delete
only want to modify nodes in place and don't care about the context.
[218] Fix | Delete
"""
[219] Fix | Delete
from collections import deque
[220] Fix | Delete
todo = deque([node])
[221] Fix | Delete
while todo:
[222] Fix | Delete
node = todo.popleft()
[223] Fix | Delete
todo.extend(iter_child_nodes(node))
[224] Fix | Delete
yield node
[225] Fix | Delete
[226] Fix | Delete
[227] Fix | Delete
class NodeVisitor(object):
[228] Fix | Delete
"""
[229] Fix | Delete
A node visitor base class that walks the abstract syntax tree and calls a
[230] Fix | Delete
visitor function for every node found. This function may return a value
[231] Fix | Delete
which is forwarded by the `visit` method.
[232] Fix | Delete
[233] Fix | Delete
This class is meant to be subclassed, with the subclass adding visitor
[234] Fix | Delete
methods.
[235] Fix | Delete
[236] Fix | Delete
Per default the visitor functions for the nodes are ``'visit_'`` +
[237] Fix | Delete
class name of the node. So a `TryFinally` node visit function would
[238] Fix | Delete
be `visit_TryFinally`. This behavior can be changed by overriding
[239] Fix | Delete
the `visit` method. If no visitor function exists for a node
[240] Fix | Delete
(return value `None`) the `generic_visit` visitor is used instead.
[241] Fix | Delete
[242] Fix | Delete
Don't use the `NodeVisitor` if you want to apply changes to nodes during
[243] Fix | Delete
traversing. For this a special visitor exists (`NodeTransformer`) that
[244] Fix | Delete
allows modifications.
[245] Fix | Delete
"""
[246] Fix | Delete
[247] Fix | Delete
def visit(self, node):
[248] Fix | Delete
"""Visit a node."""
[249] Fix | Delete
method = 'visit_' + node.__class__.__name__
[250] Fix | Delete
visitor = getattr(self, method, self.generic_visit)
[251] Fix | Delete
return visitor(node)
[252] Fix | Delete
[253] Fix | Delete
def generic_visit(self, node):
[254] Fix | Delete
"""Called if no explicit visitor function exists for a node."""
[255] Fix | Delete
for field, value in iter_fields(node):
[256] Fix | Delete
if isinstance(value, list):
[257] Fix | Delete
for item in value:
[258] Fix | Delete
if isinstance(item, AST):
[259] Fix | Delete
self.visit(item)
[260] Fix | Delete
elif isinstance(value, AST):
[261] Fix | Delete
self.visit(value)
[262] Fix | Delete
[263] Fix | Delete
[264] Fix | Delete
class NodeTransformer(NodeVisitor):
[265] Fix | Delete
"""
[266] Fix | Delete
A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
[267] Fix | Delete
allows modification of nodes.
[268] Fix | Delete
[269] Fix | Delete
The `NodeTransformer` will walk the AST and use the return value of the
[270] Fix | Delete
visitor methods to replace or remove the old node. If the return value of
[271] Fix | Delete
the visitor method is ``None``, the node will be removed from its location,
[272] Fix | Delete
otherwise it is replaced with the return value. The return value may be the
[273] Fix | Delete
original node in which case no replacement takes place.
[274] Fix | Delete
[275] Fix | Delete
Here is an example transformer that rewrites all occurrences of name lookups
[276] Fix | Delete
(``foo``) to ``data['foo']``::
[277] Fix | Delete
[278] Fix | Delete
class RewriteName(NodeTransformer):
[279] Fix | Delete
[280] Fix | Delete
def visit_Name(self, node):
[281] Fix | Delete
return copy_location(Subscript(
[282] Fix | Delete
value=Name(id='data', ctx=Load()),
[283] Fix | Delete
slice=Index(value=Str(s=node.id)),
[284] Fix | Delete
ctx=node.ctx
[285] Fix | Delete
), node)
[286] Fix | Delete
[287] Fix | Delete
Keep in mind that if the node you're operating on has child nodes you must
[288] Fix | Delete
either transform the child nodes yourself or call the :meth:`generic_visit`
[289] Fix | Delete
method for the node first.
[290] Fix | Delete
[291] Fix | Delete
For nodes that were part of a collection of statements (that applies to all
[292] Fix | Delete
statement nodes), the visitor may also return a list of nodes rather than
[293] Fix | Delete
just a single node.
[294] Fix | Delete
[295] Fix | Delete
Usually you use the transformer like this::
[296] Fix | Delete
[297] Fix | Delete
node = YourTransformer().visit(node)
[298] Fix | Delete
"""
[299] Fix | Delete
[300] Fix | Delete
def generic_visit(self, node):
[301] Fix | Delete
for field, old_value in iter_fields(node):
[302] Fix | Delete
if isinstance(old_value, list):
[303] Fix | Delete
new_values = []
[304] Fix | Delete
for value in old_value:
[305] Fix | Delete
if isinstance(value, AST):
[306] Fix | Delete
value = self.visit(value)
[307] Fix | Delete
if value is None:
[308] Fix | Delete
continue
[309] Fix | Delete
elif not isinstance(value, AST):
[310] Fix | Delete
new_values.extend(value)
[311] Fix | Delete
continue
[312] Fix | Delete
new_values.append(value)
[313] Fix | Delete
old_value[:] = new_values
[314] Fix | Delete
elif isinstance(old_value, AST):
[315] Fix | Delete
new_node = self.visit(old_value)
[316] Fix | Delete
if new_node is None:
[317] Fix | Delete
delattr(node, field)
[318] Fix | Delete
else:
[319] Fix | Delete
setattr(node, field, new_node)
[320] Fix | Delete
return node
[321] Fix | Delete
[322] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function