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