本文整理匯總了Python中ast.NodeVisitor方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.NodeVisitor方法的具體用法?Python ast.NodeVisitor怎麽用?Python ast.NodeVisitor使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ast
的用法示例。
在下文中一共展示了ast.NodeVisitor方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: parse_version
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def parse_version(fpath):
"""
Statically parse the version number from a python file
"""
import ast
if not exists(fpath):
raise ValueError('fpath={!r} does not exist'.format(fpath))
with open(fpath, 'r') as file_:
sourcecode = file_.read()
pt = ast.parse(sourcecode)
class VersionVisitor(ast.NodeVisitor):
def visit_Assign(self, node):
for target in node.targets:
if getattr(target, 'id', None) == '__version__':
self.version = node.value.s
visitor = VersionVisitor()
visitor.visit(pt)
return visitor.version
示例2: parse_version
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def parse_version(package):
"""
Statically parse the version number from __init__.py
CommandLine:
python -c "import setup; print(setup.parse_version('ovharn'))"
"""
from os.path import dirname, join
import ast
init_fpath = join(dirname(__file__), package, '__init__.py')
with open(init_fpath) as file_:
sourcecode = file_.read()
pt = ast.parse(sourcecode)
class VersionVisitor(ast.NodeVisitor):
def visit_Assign(self, node):
for target in node.targets:
if target.id == '__version__':
self.version = node.value.s
visitor = VersionVisitor()
visitor.visit(pt)
return visitor.version
示例3: visit_Call
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def visit_Call(self, node):
p = ParseCall()
p.visit(node.func)
ast.NodeVisitor.generic_visit(self, node)
if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
if node.args[0].s == "ignore":
self.bad_filters.append(
"{}:{}".format(self.__filename, node.lineno))
if p.ls[-1] == 'warn' and (
len(p.ls) == 1 or p.ls[-2] == 'warnings'):
if self.__filename == "_lib/tests/test_warnings.py":
# This file
return
# See if stacklevel exists:
if len(node.args) == 3:
return
args = {kw.arg for kw in node.keywords}
if "stacklevel" not in args:
self.bad_stacklevels.append(
"{}:{}".format(self.__filename, node.lineno))
示例4: visit_all
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def visit_all(self, nodes, inline=False):
"""Visit all nodes in the given list"""
if not inline:
last_ctx = self.context.last()
last_ctx["locals"].push()
visitor = NodeVisitor(context=self.context, config=self.config)
if isinstance(nodes, list):
for node in nodes:
visitor.visit(node)
if not inline:
self.output.append(visitor.output)
else:
visitor.visit(nodes)
if not inline:
self.output.extend(visitor.output)
if not inline:
last_ctx = self.context.last()
last_ctx["locals"].pop()
if inline:
return " ".join(visitor.output)
示例5: _parse_slice
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def _parse_slice(string):
slices = []
class SliceVisitor(ast.NodeVisitor):
def visit_Slice(self, node):
start = ast.literal_eval(node.lower) if node.lower else None
stop = ast.literal_eval(node.upper) if node.upper else None
step = ast.literal_eval(node.step) if node.step else None
slices.append(slice(start, stop, step))
try:
SliceVisitor().visit(ast.parse('_[{}]'.format(string)))
sl, = slices
except (SyntaxError, ValueError):
raise ValueError('{} is not a valid slice string'.format(string))
return sl
示例6: visit_Attribute
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def visit_Attribute(self, node): # pylint: disable=invalid-name
"""Handle bare Attributes i.e. [tf.foo, tf.bar].
Args:
node: Node that is of type ast.Attribute
"""
full_name = self._get_attribute_full_path(node)
if full_name and full_name.startswith("tf."):
self._rename_functions(node, full_name)
if full_name in self._api_change_spec.change_to_function:
if not hasattr(node, "is_function_for_call"):
new_text = full_name + "()"
self._file_edit.add("Changed %r to %r"%(full_name, new_text),
node.lineno, node.col_offset, full_name, new_text)
ast.NodeVisitor.generic_visit(self, node)
示例7: visit_Subscript
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def visit_Subscript(self, node):
if hasattr(node.slice, 'value') and hasattr(node.slice.value, 'id'):
self.stack.append('[' + str(node.slice.value.id) + ']')
self.in_subscript += 1
self.seen_name = False
elif hasattr(node.slice, 'value') and hasattr(node.slice.value, 'n'):
self.stack.append('[' + str(node.slice.value.n) + ']')
self.in_subscript += 1
self.seen_name = False
elif hasattr(node.slice, 'value') and hasattr(node.slice.value, 's'):
self.stack.append('[' + repr(str(node.slice.value.s)) + ']')
self.in_subscript += 1
self.seen_name = False
else:
self.seen_complexity = 1
ast.NodeVisitor.generic_visit(self, node)
if hasattr(node.slice, 'slice') and (hasattr(node.slice.value, 'id') or hasattr(node.slice.value, 'n')):
self.in_subscript -= 1
示例8: visit_Assign
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def visit_Assign(self, node):
for key, val in ast.iter_fields(node):
if key == 'targets':
for subnode in val:
if type(subnode) is ast.Tuple:
for subsubnode in subnode.elts:
crawler = myextract()
crawler.visit(subsubnode)
self.targets[fix_assign.sub(r'\1', ".".join(reversed(crawler.stack)))] = 1
else:
crawler = myextract()
crawler.visit(subnode)
self.targets[fix_assign.sub(r'\1', ".".join(reversed(crawler.stack)))] = 1
self.depth += 1
#ast.NodeVisitor.generic_visit(self, node)
self.generic_visit(node)
self.depth -= 1
示例9: from_code
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def from_code(cls, code, **kwargs):
'''Instanciate the class from source code (string object). The
`**kwargs` are directly passed to the `ast.NodeVisitor` constructor.
'''
return cls.from_ast(code2ast(code), **kwargs)
示例10: from_ast
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def from_ast(cls, ast_node, **kwargs):
'''Instantiate the class from an AST node. The `**kwargs` are
directly passed to the `ast.NodeVisitor` constructor.
'''
visitor = cls(**kwargs)
visitor.visit(ast_node)
return visitor
示例11: visit_Attribute
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def visit_Attribute(self, node):
ast.NodeVisitor.generic_visit(self, node)
self.ls.append(node.attr)
示例12: visit_Call
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def visit_Call(self, node):
p = ParseCall()
p.visit(node.func)
ast.NodeVisitor.generic_visit(self, node)
if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
if node.args[0].s == "ignore":
raise AssertionError(
"ignore filter should not be used; found in "
"{} on line {}".format(self.__filename, node.lineno))
if p.ls[-1] == 'warn' and (
len(p.ls) == 1 or p.ls[-2] == 'warnings'):
if "testing/tests/test_warnings.py" is self.__filename:
# This file
return
# See if stacklevel exists:
if len(node.args) == 3:
return
args = {kw.arg for kw in node.keywords}
if "stacklevel" in args:
return
raise AssertionError(
"warnings should have an appropriate stacklevel; found in "
"{} on line {}".format(self.__filename, node.lineno))
示例13: generic_visit
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def generic_visit(self, node):
lineno = getattr(node, 'lineno', 0)
self.boundary = max(self.boundary, lineno)
ast.NodeVisitor.generic_visit(self, node)
示例14: scan_opcodes_cli
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def scan_opcodes_cli(self, co):
import ast
with open(co.co_filename, 'rU') as f:
nodes = ast.parse(f.read(), co.co_filename)
items = []
class ModuleFinderVisitor(ast.NodeVisitor):
def visit_Assign(self, node):
for x in node.targets:
if isinstance(x, ast.Subscript):
if isinstance(x.value, ast.Name):
items.append(("store", (x.value.id, )))
elif isinstance(x.value, ast.Attribute):
items.append(("store", (x.value.attr, )))
else:
print 'Unknown in store: %s' % type(x.value).__name__
elif isinstance(x, ast.Name):
items.append(("store", (x.id, )))
def visit_Import(self, node):
items.extend([("import", (None, x.name)) for x in node.names])
def visit_ImportFrom(self, node):
if node.level == 1:
items.append(("relative_import", (node.level, [x.name for x in node.names], node.module)))
else:
items.extend([("import", ([x.name for x in node.names], node.module))])
v = ModuleFinderVisitor()
v.visit(nodes)
for what, args in items:
yield what, args
示例15: visit
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NodeVisitor [as 別名]
def visit(self, node):
# We could have subclassed ast.NodeVisitor, but it's better to fail
# hard on AST nodes we don't support
name = node.__class__.__name__
visit_func = getattr(self, 'visit_' + name, None)
assert visit_func is not None, '{} not supported - node {}'.format(
name, ast.dump(node))
visit_func(node)