Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/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
import sys
[26] Fix | Delete
from _ast import *
[27] Fix | Delete
from contextlib import contextmanager, nullcontext
[28] Fix | Delete
from enum import IntEnum, auto
[29] Fix | Delete
[30] Fix | Delete
[31] Fix | Delete
def parse(source, filename='<unknown>', mode='exec', *,
[32] Fix | Delete
type_comments=False, feature_version=None):
[33] Fix | Delete
"""
[34] Fix | Delete
Parse the source into an AST node.
[35] Fix | Delete
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
[36] Fix | Delete
Pass type_comments=True to get back type comments where the syntax allows.
[37] Fix | Delete
"""
[38] Fix | Delete
flags = PyCF_ONLY_AST
[39] Fix | Delete
if type_comments:
[40] Fix | Delete
flags |= PyCF_TYPE_COMMENTS
[41] Fix | Delete
if isinstance(feature_version, tuple):
[42] Fix | Delete
major, minor = feature_version # Should be a 2-tuple.
[43] Fix | Delete
assert major == 3
[44] Fix | Delete
feature_version = minor
[45] Fix | Delete
elif feature_version is None:
[46] Fix | Delete
feature_version = -1
[47] Fix | Delete
# Else it should be an int giving the minor version for 3.x.
[48] Fix | Delete
return compile(source, filename, mode, flags,
[49] Fix | Delete
_feature_version=feature_version)
[50] Fix | Delete
[51] Fix | Delete
[52] Fix | Delete
def literal_eval(node_or_string):
[53] Fix | Delete
"""
[54] Fix | Delete
Safely evaluate an expression node or a string containing a Python
[55] Fix | Delete
expression. The string or node provided may only consist of the following
[56] Fix | Delete
Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
[57] Fix | Delete
sets, booleans, and None.
[58] Fix | Delete
"""
[59] Fix | Delete
if isinstance(node_or_string, str):
[60] Fix | Delete
node_or_string = parse(node_or_string, mode='eval')
[61] Fix | Delete
if isinstance(node_or_string, Expression):
[62] Fix | Delete
node_or_string = node_or_string.body
[63] Fix | Delete
def _raise_malformed_node(node):
[64] Fix | Delete
raise ValueError(f'malformed node or string: {node!r}')
[65] Fix | Delete
def _convert_num(node):
[66] Fix | Delete
if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
[67] Fix | Delete
_raise_malformed_node(node)
[68] Fix | Delete
return node.value
[69] Fix | Delete
def _convert_signed_num(node):
[70] Fix | Delete
if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
[71] Fix | Delete
operand = _convert_num(node.operand)
[72] Fix | Delete
if isinstance(node.op, UAdd):
[73] Fix | Delete
return + operand
[74] Fix | Delete
else:
[75] Fix | Delete
return - operand
[76] Fix | Delete
return _convert_num(node)
[77] Fix | Delete
def _convert(node):
[78] Fix | Delete
if isinstance(node, Constant):
[79] Fix | Delete
return node.value
[80] Fix | Delete
elif isinstance(node, Tuple):
[81] Fix | Delete
return tuple(map(_convert, node.elts))
[82] Fix | Delete
elif isinstance(node, List):
[83] Fix | Delete
return list(map(_convert, node.elts))
[84] Fix | Delete
elif isinstance(node, Set):
[85] Fix | Delete
return set(map(_convert, node.elts))
[86] Fix | Delete
elif (isinstance(node, Call) and isinstance(node.func, Name) and
[87] Fix | Delete
node.func.id == 'set' and node.args == node.keywords == []):
[88] Fix | Delete
return set()
[89] Fix | Delete
elif isinstance(node, Dict):
[90] Fix | Delete
if len(node.keys) != len(node.values):
[91] Fix | Delete
_raise_malformed_node(node)
[92] Fix | Delete
return dict(zip(map(_convert, node.keys),
[93] Fix | Delete
map(_convert, node.values)))
[94] Fix | Delete
elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
[95] Fix | Delete
left = _convert_signed_num(node.left)
[96] Fix | Delete
right = _convert_num(node.right)
[97] Fix | Delete
if isinstance(left, (int, float)) and isinstance(right, complex):
[98] Fix | Delete
if isinstance(node.op, Add):
[99] Fix | Delete
return left + right
[100] Fix | Delete
else:
[101] Fix | Delete
return left - right
[102] Fix | Delete
return _convert_signed_num(node)
[103] Fix | Delete
return _convert(node_or_string)
[104] Fix | Delete
[105] Fix | Delete
[106] Fix | Delete
def dump(node, annotate_fields=True, include_attributes=False, *, indent=None):
[107] Fix | Delete
"""
[108] Fix | Delete
Return a formatted dump of the tree in node. This is mainly useful for
[109] Fix | Delete
debugging purposes. If annotate_fields is true (by default),
[110] Fix | Delete
the returned string will show the names and the values for fields.
[111] Fix | Delete
If annotate_fields is false, the result string will be more compact by
[112] Fix | Delete
omitting unambiguous field names. Attributes such as line
[113] Fix | Delete
numbers and column offsets are not dumped by default. If this is wanted,
[114] Fix | Delete
include_attributes can be set to true. If indent is a non-negative
[115] Fix | Delete
integer or string, then the tree will be pretty-printed with that indent
[116] Fix | Delete
level. None (the default) selects the single line representation.
[117] Fix | Delete
"""
[118] Fix | Delete
def _format(node, level=0):
[119] Fix | Delete
if indent is not None:
[120] Fix | Delete
level += 1
[121] Fix | Delete
prefix = '\n' + indent * level
[122] Fix | Delete
sep = ',\n' + indent * level
[123] Fix | Delete
else:
[124] Fix | Delete
prefix = ''
[125] Fix | Delete
sep = ', '
[126] Fix | Delete
if isinstance(node, AST):
[127] Fix | Delete
cls = type(node)
[128] Fix | Delete
args = []
[129] Fix | Delete
allsimple = True
[130] Fix | Delete
keywords = annotate_fields
[131] Fix | Delete
for name in node._fields:
[132] Fix | Delete
try:
[133] Fix | Delete
value = getattr(node, name)
[134] Fix | Delete
except AttributeError:
[135] Fix | Delete
keywords = True
[136] Fix | Delete
continue
[137] Fix | Delete
if value is None and getattr(cls, name, ...) is None:
[138] Fix | Delete
keywords = True
[139] Fix | Delete
continue
[140] Fix | Delete
value, simple = _format(value, level)
[141] Fix | Delete
allsimple = allsimple and simple
[142] Fix | Delete
if keywords:
[143] Fix | Delete
args.append('%s=%s' % (name, value))
[144] Fix | Delete
else:
[145] Fix | Delete
args.append(value)
[146] Fix | Delete
if include_attributes and node._attributes:
[147] Fix | Delete
for name in node._attributes:
[148] Fix | Delete
try:
[149] Fix | Delete
value = getattr(node, name)
[150] Fix | Delete
except AttributeError:
[151] Fix | Delete
continue
[152] Fix | Delete
if value is None and getattr(cls, name, ...) is None:
[153] Fix | Delete
continue
[154] Fix | Delete
value, simple = _format(value, level)
[155] Fix | Delete
allsimple = allsimple and simple
[156] Fix | Delete
args.append('%s=%s' % (name, value))
[157] Fix | Delete
if allsimple and len(args) <= 3:
[158] Fix | Delete
return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args
[159] Fix | Delete
return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False
[160] Fix | Delete
elif isinstance(node, list):
[161] Fix | Delete
if not node:
[162] Fix | Delete
return '[]', True
[163] Fix | Delete
return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False
[164] Fix | Delete
return repr(node), True
[165] Fix | Delete
[166] Fix | Delete
if not isinstance(node, AST):
[167] Fix | Delete
raise TypeError('expected AST, got %r' % node.__class__.__name__)
[168] Fix | Delete
if indent is not None and not isinstance(indent, str):
[169] Fix | Delete
indent = ' ' * indent
[170] Fix | Delete
return _format(node)[0]
[171] Fix | Delete
[172] Fix | Delete
[173] Fix | Delete
def copy_location(new_node, old_node):
[174] Fix | Delete
"""
[175] Fix | Delete
Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
[176] Fix | Delete
attributes) from *old_node* to *new_node* if possible, and return *new_node*.
[177] Fix | Delete
"""
[178] Fix | Delete
for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
[179] Fix | Delete
if attr in old_node._attributes and attr in new_node._attributes:
[180] Fix | Delete
value = getattr(old_node, attr, None)
[181] Fix | Delete
# end_lineno and end_col_offset are optional attributes, and they
[182] Fix | Delete
# should be copied whether the value is None or not.
[183] Fix | Delete
if value is not None or (
[184] Fix | Delete
hasattr(old_node, attr) and attr.startswith("end_")
[185] Fix | Delete
):
[186] Fix | Delete
setattr(new_node, attr, value)
[187] Fix | Delete
return new_node
[188] Fix | Delete
[189] Fix | Delete
[190] Fix | Delete
def fix_missing_locations(node):
[191] Fix | Delete
"""
[192] Fix | Delete
When you compile a node tree with compile(), the compiler expects lineno and
[193] Fix | Delete
col_offset attributes for every node that supports them. This is rather
[194] Fix | Delete
tedious to fill in for generated nodes, so this helper adds these attributes
[195] Fix | Delete
recursively where not already set, by setting them to the values of the
[196] Fix | Delete
parent node. It works recursively starting at *node*.
[197] Fix | Delete
"""
[198] Fix | Delete
def _fix(node, lineno, col_offset, end_lineno, end_col_offset):
[199] Fix | Delete
if 'lineno' in node._attributes:
[200] Fix | Delete
if not hasattr(node, 'lineno'):
[201] Fix | Delete
node.lineno = lineno
[202] Fix | Delete
else:
[203] Fix | Delete
lineno = node.lineno
[204] Fix | Delete
if 'end_lineno' in node._attributes:
[205] Fix | Delete
if getattr(node, 'end_lineno', None) is None:
[206] Fix | Delete
node.end_lineno = end_lineno
[207] Fix | Delete
else:
[208] Fix | Delete
end_lineno = node.end_lineno
[209] Fix | Delete
if 'col_offset' in node._attributes:
[210] Fix | Delete
if not hasattr(node, 'col_offset'):
[211] Fix | Delete
node.col_offset = col_offset
[212] Fix | Delete
else:
[213] Fix | Delete
col_offset = node.col_offset
[214] Fix | Delete
if 'end_col_offset' in node._attributes:
[215] Fix | Delete
if getattr(node, 'end_col_offset', None) is None:
[216] Fix | Delete
node.end_col_offset = end_col_offset
[217] Fix | Delete
else:
[218] Fix | Delete
end_col_offset = node.end_col_offset
[219] Fix | Delete
for child in iter_child_nodes(node):
[220] Fix | Delete
_fix(child, lineno, col_offset, end_lineno, end_col_offset)
[221] Fix | Delete
_fix(node, 1, 0, 1, 0)
[222] Fix | Delete
return node
[223] Fix | Delete
[224] Fix | Delete
[225] Fix | Delete
def increment_lineno(node, n=1):
[226] Fix | Delete
"""
[227] Fix | Delete
Increment the line number and end line number of each node in the tree
[228] Fix | Delete
starting at *node* by *n*. This is useful to "move code" to a different
[229] Fix | Delete
location in a file.
[230] Fix | Delete
"""
[231] Fix | Delete
for child in walk(node):
[232] Fix | Delete
if 'lineno' in child._attributes:
[233] Fix | Delete
child.lineno = getattr(child, 'lineno', 0) + n
[234] Fix | Delete
if (
[235] Fix | Delete
"end_lineno" in child._attributes
[236] Fix | Delete
and (end_lineno := getattr(child, "end_lineno", 0)) is not None
[237] Fix | Delete
):
[238] Fix | Delete
child.end_lineno = end_lineno + n
[239] Fix | Delete
return node
[240] Fix | Delete
[241] Fix | Delete
[242] Fix | Delete
def iter_fields(node):
[243] Fix | Delete
"""
[244] Fix | Delete
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
[245] Fix | Delete
that is present on *node*.
[246] Fix | Delete
"""
[247] Fix | Delete
for field in node._fields:
[248] Fix | Delete
try:
[249] Fix | Delete
yield field, getattr(node, field)
[250] Fix | Delete
except AttributeError:
[251] Fix | Delete
pass
[252] Fix | Delete
[253] Fix | Delete
[254] Fix | Delete
def iter_child_nodes(node):
[255] Fix | Delete
"""
[256] Fix | Delete
Yield all direct child nodes of *node*, that is, all fields that are nodes
[257] Fix | Delete
and all items of fields that are lists of nodes.
[258] Fix | Delete
"""
[259] Fix | Delete
for name, field in iter_fields(node):
[260] Fix | Delete
if isinstance(field, AST):
[261] Fix | Delete
yield field
[262] Fix | Delete
elif isinstance(field, list):
[263] Fix | Delete
for item in field:
[264] Fix | Delete
if isinstance(item, AST):
[265] Fix | Delete
yield item
[266] Fix | Delete
[267] Fix | Delete
[268] Fix | Delete
def get_docstring(node, clean=True):
[269] Fix | Delete
"""
[270] Fix | Delete
Return the docstring for the given node or None if no docstring can
[271] Fix | Delete
be found. If the node provided does not have docstrings a TypeError
[272] Fix | Delete
will be raised.
[273] Fix | Delete
[274] Fix | Delete
If *clean* is `True`, all tabs are expanded to spaces and any whitespace
[275] Fix | Delete
that can be uniformly removed from the second line onwards is removed.
[276] Fix | Delete
"""
[277] Fix | Delete
if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
[278] Fix | Delete
raise TypeError("%r can't have docstrings" % node.__class__.__name__)
[279] Fix | Delete
if not(node.body and isinstance(node.body[0], Expr)):
[280] Fix | Delete
return None
[281] Fix | Delete
node = node.body[0].value
[282] Fix | Delete
if isinstance(node, Str):
[283] Fix | Delete
text = node.s
[284] Fix | Delete
elif isinstance(node, Constant) and isinstance(node.value, str):
[285] Fix | Delete
text = node.value
[286] Fix | Delete
else:
[287] Fix | Delete
return None
[288] Fix | Delete
if clean:
[289] Fix | Delete
import inspect
[290] Fix | Delete
text = inspect.cleandoc(text)
[291] Fix | Delete
return text
[292] Fix | Delete
[293] Fix | Delete
[294] Fix | Delete
def _splitlines_no_ff(source):
[295] Fix | Delete
"""Split a string into lines ignoring form feed and other chars.
[296] Fix | Delete
[297] Fix | Delete
This mimics how the Python parser splits source code.
[298] Fix | Delete
"""
[299] Fix | Delete
idx = 0
[300] Fix | Delete
lines = []
[301] Fix | Delete
next_line = ''
[302] Fix | Delete
while idx < len(source):
[303] Fix | Delete
c = source[idx]
[304] Fix | Delete
next_line += c
[305] Fix | Delete
idx += 1
[306] Fix | Delete
# Keep \r\n together
[307] Fix | Delete
if c == '\r' and idx < len(source) and source[idx] == '\n':
[308] Fix | Delete
next_line += '\n'
[309] Fix | Delete
idx += 1
[310] Fix | Delete
if c in '\r\n':
[311] Fix | Delete
lines.append(next_line)
[312] Fix | Delete
next_line = ''
[313] Fix | Delete
[314] Fix | Delete
if next_line:
[315] Fix | Delete
lines.append(next_line)
[316] Fix | Delete
return lines
[317] Fix | Delete
[318] Fix | Delete
[319] Fix | Delete
def _pad_whitespace(source):
[320] Fix | Delete
r"""Replace all chars except '\f\t' in a line with spaces."""
[321] Fix | Delete
result = ''
[322] Fix | Delete
for c in source:
[323] Fix | Delete
if c in '\f\t':
[324] Fix | Delete
result += c
[325] Fix | Delete
else:
[326] Fix | Delete
result += ' '
[327] Fix | Delete
return result
[328] Fix | Delete
[329] Fix | Delete
[330] Fix | Delete
def get_source_segment(source, node, *, padded=False):
[331] Fix | Delete
"""Get source code segment of the *source* that generated *node*.
[332] Fix | Delete
[333] Fix | Delete
If some location information (`lineno`, `end_lineno`, `col_offset`,
[334] Fix | Delete
or `end_col_offset`) is missing, return None.
[335] Fix | Delete
[336] Fix | Delete
If *padded* is `True`, the first line of a multi-line statement will
[337] Fix | Delete
be padded with spaces to match its original position.
[338] Fix | Delete
"""
[339] Fix | Delete
try:
[340] Fix | Delete
if node.end_lineno is None or node.end_col_offset is None:
[341] Fix | Delete
return None
[342] Fix | Delete
lineno = node.lineno - 1
[343] Fix | Delete
end_lineno = node.end_lineno - 1
[344] Fix | Delete
col_offset = node.col_offset
[345] Fix | Delete
end_col_offset = node.end_col_offset
[346] Fix | Delete
except AttributeError:
[347] Fix | Delete
return None
[348] Fix | Delete
[349] Fix | Delete
lines = _splitlines_no_ff(source)
[350] Fix | Delete
if end_lineno == lineno:
[351] Fix | Delete
return lines[lineno].encode()[col_offset:end_col_offset].decode()
[352] Fix | Delete
[353] Fix | Delete
if padded:
[354] Fix | Delete
padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())
[355] Fix | Delete
else:
[356] Fix | Delete
padding = ''
[357] Fix | Delete
[358] Fix | Delete
first = padding + lines[lineno].encode()[col_offset:].decode()
[359] Fix | Delete
last = lines[end_lineno].encode()[:end_col_offset].decode()
[360] Fix | Delete
lines = lines[lineno+1:end_lineno]
[361] Fix | Delete
[362] Fix | Delete
lines.insert(0, first)
[363] Fix | Delete
lines.append(last)
[364] Fix | Delete
return ''.join(lines)
[365] Fix | Delete
[366] Fix | Delete
[367] Fix | Delete
def walk(node):
[368] Fix | Delete
"""
[369] Fix | Delete
Recursively yield all descendant nodes in the tree starting at *node*
[370] Fix | Delete
(including *node* itself), in no specified order. This is useful if you
[371] Fix | Delete
only want to modify nodes in place and don't care about the context.
[372] Fix | Delete
"""
[373] Fix | Delete
from collections import deque
[374] Fix | Delete
todo = deque([node])
[375] Fix | Delete
while todo:
[376] Fix | Delete
node = todo.popleft()
[377] Fix | Delete
todo.extend(iter_child_nodes(node))
[378] Fix | Delete
yield node
[379] Fix | Delete
[380] Fix | Delete
[381] Fix | Delete
class NodeVisitor(object):
[382] Fix | Delete
"""
[383] Fix | Delete
A node visitor base class that walks the abstract syntax tree and calls a
[384] Fix | Delete
visitor function for every node found. This function may return a value
[385] Fix | Delete
which is forwarded by the `visit` method.
[386] Fix | Delete
[387] Fix | Delete
This class is meant to be subclassed, with the subclass adding visitor
[388] Fix | Delete
methods.
[389] Fix | Delete
[390] Fix | Delete
Per default the visitor functions for the nodes are ``'visit_'`` +
[391] Fix | Delete
class name of the node. So a `TryFinally` node visit function would
[392] Fix | Delete
be `visit_TryFinally`. This behavior can be changed by overriding
[393] Fix | Delete
the `visit` method. If no visitor function exists for a node
[394] Fix | Delete
(return value `None`) the `generic_visit` visitor is used instead.
[395] Fix | Delete
[396] Fix | Delete
Don't use the `NodeVisitor` if you want to apply changes to nodes during
[397] Fix | Delete
traversing. For this a special visitor exists (`NodeTransformer`) that
[398] Fix | Delete
allows modifications.
[399] Fix | Delete
"""
[400] Fix | Delete
[401] Fix | Delete
def visit(self, node):
[402] Fix | Delete
"""Visit a node."""
[403] Fix | Delete
method = 'visit_' + node.__class__.__name__
[404] Fix | Delete
visitor = getattr(self, method, self.generic_visit)
[405] Fix | Delete
return visitor(node)
[406] Fix | Delete
[407] Fix | Delete
def generic_visit(self, node):
[408] Fix | Delete
"""Called if no explicit visitor function exists for a node."""
[409] Fix | Delete
for field, value in iter_fields(node):
[410] Fix | Delete
if isinstance(value, list):
[411] Fix | Delete
for item in value:
[412] Fix | Delete
if isinstance(item, AST):
[413] Fix | Delete
self.visit(item)
[414] Fix | Delete
elif isinstance(value, AST):
[415] Fix | Delete
self.visit(value)
[416] Fix | Delete
[417] Fix | Delete
def visit_Constant(self, node):
[418] Fix | Delete
value = node.value
[419] Fix | Delete
type_name = _const_node_type_names.get(type(value))
[420] Fix | Delete
if type_name is None:
[421] Fix | Delete
for cls, name in _const_node_type_names.items():
[422] Fix | Delete
if isinstance(value, cls):
[423] Fix | Delete
type_name = name
[424] Fix | Delete
break
[425] Fix | Delete
if type_name is not None:
[426] Fix | Delete
method = 'visit_' + type_name
[427] Fix | Delete
try:
[428] Fix | Delete
visitor = getattr(self, method)
[429] Fix | Delete
except AttributeError:
[430] Fix | Delete
pass
[431] Fix | Delete
else:
[432] Fix | Delete
import warnings
[433] Fix | Delete
warnings.warn(f"{method} is deprecated; add visit_Constant",
[434] Fix | Delete
DeprecationWarning, 2)
[435] Fix | Delete
return visitor(node)
[436] Fix | Delete
return self.generic_visit(node)
[437] Fix | Delete
[438] Fix | Delete
[439] Fix | Delete
class NodeTransformer(NodeVisitor):
[440] Fix | Delete
"""
[441] Fix | Delete
A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
[442] Fix | Delete
allows modification of nodes.
[443] Fix | Delete
[444] Fix | Delete
The `NodeTransformer` will walk the AST and use the return value of the
[445] Fix | Delete
visitor methods to replace or remove the old node. If the return value of
[446] Fix | Delete
the visitor method is ``None``, the node will be removed from its location,
[447] Fix | Delete
otherwise it is replaced with the return value. The return value may be the
[448] Fix | Delete
original node in which case no replacement takes place.
[449] Fix | Delete
[450] Fix | Delete
Here is an example transformer that rewrites all occurrences of name lookups
[451] Fix | Delete
(``foo``) to ``data['foo']``::
[452] Fix | Delete
[453] Fix | Delete
class RewriteName(NodeTransformer):
[454] Fix | Delete
[455] Fix | Delete
def visit_Name(self, node):
[456] Fix | Delete
return Subscript(
[457] Fix | Delete
value=Name(id='data', ctx=Load()),
[458] Fix | Delete
slice=Constant(value=node.id),
[459] Fix | Delete
ctx=node.ctx
[460] Fix | Delete
)
[461] Fix | Delete
[462] Fix | Delete
Keep in mind that if the node you're operating on has child nodes you must
[463] Fix | Delete
either transform the child nodes yourself or call the :meth:`generic_visit`
[464] Fix | Delete
method for the node first.
[465] Fix | Delete
[466] Fix | Delete
For nodes that were part of a collection of statements (that applies to all
[467] Fix | Delete
statement nodes), the visitor may also return a list of nodes rather than
[468] Fix | Delete
just a single node.
[469] Fix | Delete
[470] Fix | Delete
Usually you use the transformer like this::
[471] Fix | Delete
[472] Fix | Delete
node = YourTransformer().visit(node)
[473] Fix | Delete
"""
[474] Fix | Delete
[475] Fix | Delete
def generic_visit(self, node):
[476] Fix | Delete
for field, old_value in iter_fields(node):
[477] Fix | Delete
if isinstance(old_value, list):
[478] Fix | Delete
new_values = []
[479] Fix | Delete
for value in old_value:
[480] Fix | Delete
if isinstance(value, AST):
[481] Fix | Delete
value = self.visit(value)
[482] Fix | Delete
if value is None:
[483] Fix | Delete
continue
[484] Fix | Delete
elif not isinstance(value, AST):
[485] Fix | Delete
new_values.extend(value)
[486] Fix | Delete
continue
[487] Fix | Delete
new_values.append(value)
[488] Fix | Delete
old_value[:] = new_values
[489] Fix | Delete
elif isinstance(old_value, AST):
[490] Fix | Delete
new_node = self.visit(old_value)
[491] Fix | Delete
if new_node is None:
[492] Fix | Delete
delattr(node, field)
[493] Fix | Delete
else:
[494] Fix | Delete
setattr(node, field, new_node)
[495] Fix | Delete
return node
[496] Fix | Delete
[497] Fix | Delete
[498] Fix | Delete
# If the ast module is loaded more than once, only add deprecated methods once
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function