本文整理汇总了Python中ast.List方法的典型用法代码示例。如果您正苦于以下问题:Python ast.List方法的具体用法?Python ast.List怎么用?Python ast.List使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.List方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TRY
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
示例2: comp_op_rewrite
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def comp_op_rewrite(op: t.Union[Tokenizer, t.List[Tokenizer]]):
"""
('<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not')
"""
if isinstance(op, list):
op = tuple(map(lambda it: it.value, op))
else:
op = op.value
return {
'<': ast.Lt,
'>': ast.Gt,
'==': ast.Eq,
'>=': ast.GtE,
'<=': ast.LtE,
'<>': lambda: raise_exp(NotImplemented),
'!=': ast.NotEq,
'in': ast.In,
('is', ): ast.Is,
('is', 'not'): ast.IsNot,
('not', 'in'): ast.NotIn,
}[op]()
示例3: _get_value_from_ast
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def _get_value_from_ast(self, obj):
"""
Return the value of the ast object.
"""
if isinstance(obj, ast.Num):
return obj.n
elif isinstance(obj, ast.Str):
return obj.s
elif isinstance(obj, ast.List):
return [self._get_value_from_ast(e) for e in obj.elts]
elif isinstance(obj, ast.Tuple):
return tuple([self._get_value_from_ast(e) for e in obj.elts])
# None, True and False are NameConstants in Py3.4 and above.
elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant):
return obj.value
# For python versions below 3.4
elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]):
return string_to_constant[obj.id]
# Probably passed a variable name.
# Or passed a single word without wrapping it in quotes as an argument
# ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')")
raise NameError("name '%s' is not defined" % obj.id)
示例4: read_from_directory
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def read_from_directory(
cls, directory
): # type: (Union[basestring, Path]) -> Dict[str, Union[List, Dict]]
if isinstance(directory, basestring):
directory = Path(directory)
result = cls.DEFAULT.copy()
for filename in cls.FILES:
filepath = directory / filename
if not filepath.exists():
continue
new_result = getattr(cls(), "read_{}".format(filename.replace(".", "_")))(
filepath
)
for key in result.keys():
if new_result[key]:
result[key] = new_result[key]
return result
示例5: _find_sub_setup_call
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def _find_sub_setup_call(
self, elements
): # type: (List[Any]) -> Tuple[Optional[ast.Call], Optional[List[Any]]]
for element in elements:
if not isinstance(element, (ast.FunctionDef, ast.If)):
continue
setup_call = self._find_setup_call(element.body)
if setup_call != (None, None):
setup_call, body = setup_call
body = elements + body
return setup_call, body
return None, None
示例6: __init__
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def __init__(self,
symbol_table: SymbolTable,
custom_types_symbol_table: SymbolTable,
external_ir2_symbols_by_name_by_module: Dict[str, Dict[str, Union[ir2.FunctionDefn, ir2.CustomType]]],
filename: str,
source_lines: List[str],
identifier_generator: Iterator[str],
function_name: Optional[str] = None,
function_definition_line: Optional[int] = None,
first_enclosing_except_stmt_line: Optional[int] = None,
partially_typechecked_function_definitions_by_name: Dict[str, ast.FunctionDef] = None):
assert (function_name is None) == (function_definition_line is None)
self.symbol_table = symbol_table
self.custom_types_symbol_table = custom_types_symbol_table
self.external_ir2_symbols_by_name_by_module = external_ir2_symbols_by_name_by_module
self.partially_typechecked_function_definitions_by_name = partially_typechecked_function_definitions_by_name or dict()
self.filename = filename
self.source_lines = source_lines
self.current_function_name = function_name
self.current_function_definition_line = function_definition_line
self.first_enclosing_except_stmt_line = first_enclosing_except_stmt_line
self.identifier_generator = identifier_generator
示例7: read_from_directory
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def read_from_directory(
cls, directory
): # type: (Union[str, Path]) -> Dict[str, Union[List, Dict]]
if isinstance(directory, str):
directory = Path(directory)
result = cls.DEFAULT.copy()
for filename in cls.FILES:
filepath = directory / filename
if not filepath.exists():
continue
new_result = getattr(cls(), "read_{}".format(filename.replace(".", "_")))(
filepath
)
for key in result.keys():
if new_result[key]:
result[key] = new_result[key]
return result
示例8: _process_set_empty_literal
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def _process_set_empty_literal(tokens: List[Token], start: int) -> None:
if _is_wtf('set', tokens, start):
return
i = start + 2
brace_stack = ['(']
while brace_stack:
token = tokens[i].src
if token == BRACES[brace_stack[-1]]:
brace_stack.pop()
elif token in BRACES:
brace_stack.append(token)
elif '\n' in token:
# Contains a newline, could cause a SyntaxError, bail
return
i += 1
# Remove the inner tokens
del tokens[start + 2:i - 1]
示例9: _process_set_literal
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def _process_set_literal(
tokens: List[Token],
start: int,
arg: ast.expr,
) -> None:
if _is_wtf('set', tokens, start):
return
gen = isinstance(arg, ast.GeneratorExp)
set_victims = _victims(tokens, start + 1, arg, gen=gen)
del set_victims.starts[0]
end_index = set_victims.ends.pop()
tokens[end_index] = Token('OP', '}')
for index in reversed(set_victims.starts + set_victims.ends):
_remove_brace(tokens, index)
tokens[start:start + 2] = [Token('OP', '{')]
示例10: visit_Call
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def visit_Call(self, node: ast.Call) -> None:
if (
isinstance(node.func, ast.Name) and
node.func.id == 'set' and
len(node.args) == 1 and
not node.keywords and
isinstance(node.args[0], SET_TRANSFORM)
):
arg, = node.args
key = _ast_to_offset(node.func)
if isinstance(arg, (ast.List, ast.Tuple)) and not arg.elts:
self.set_empty_literals[key] = arg
else:
self.sets[key] = arg
elif (
isinstance(node.func, ast.Name) and
node.func.id == 'dict' and
len(node.args) == 1 and
not node.keywords and
isinstance(node.args[0], (ast.ListComp, ast.GeneratorExp)) and
isinstance(node.args[0].elt, (ast.Tuple, ast.List)) and
len(node.args[0].elt.elts) == 2
):
self.dicts[_ast_to_offset(node.func)] = node.args[0]
self.generic_visit(node)
示例11: _fix_percent_format_tuple
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def _fix_percent_format_tuple(
tokens: List[Token],
start: int,
node: ast.BinOp,
) -> None:
# TODO: this is overly timid
paren = start + 4
if tokens_to_src(tokens[start + 1:paren + 1]) != ' % (':
return
victims = _victims(tokens, paren, node.right, gen=False)
victims.ends.pop()
for index in reversed(victims.starts + victims.ends):
_remove_brace(tokens, index)
newsrc = _percent_to_format(tokens[start].src)
tokens[start] = tokens[start]._replace(src=newsrc)
tokens[start + 1:paren] = [Token('Format', '.format'), Token('OP', '(')]
示例12: _compare_to_3
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def _compare_to_3(
test: ast.Compare,
op: Union[Type[ast.cmpop], Tuple[Type[ast.cmpop], ...]],
) -> bool:
if not (
isinstance(test.ops[0], op) and
isinstance(test.comparators[0], ast.Tuple) and
len(test.comparators[0].elts) >= 1 and
all(isinstance(n, ast.Num) for n in test.comparators[0].elts)
):
return False
# checked above but mypy needs help
elts = cast('List[ast.Num]', test.comparators[0].elts)
return elts[0].n == 3 and all(n.n == 0 for n in elts[1:])
示例13: _trim_end
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def _trim_end(self, tokens: List[Token]) -> 'Block':
"""the tokenizer reports the end of the block at the beginning of
the next block
"""
i = last_token = self.end - 1
while tokens[i].name in NON_CODING_TOKENS | {'DEDENT', 'NEWLINE'}:
# if we find an indented comment inside our block, keep it
if (
tokens[i].name in {'NL', 'NEWLINE'} and
tokens[i + 1].name == UNIMPORTANT_WS and
len(tokens[i + 1].src) > self._initial_indent(tokens)
):
break
# otherwise we've found another line to remove
elif tokens[i].name in {'NL', 'NEWLINE'}:
last_token = i
i -= 1
return self._replace(end=last_token + 1)
示例14: _replace_call
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def _replace_call(
tokens: List[Token],
start: int,
end: int,
args: List[Tuple[int, int]],
tmpl: str,
) -> None:
arg_strs = [_arg_str(tokens, *arg) for arg in args]
start_rest = args[0][1] + 1
while (
start_rest < end and
tokens[start_rest].name in {'COMMENT', UNIMPORTANT_WS}
):
start_rest += 1
rest = tokens_to_src(tokens[start_rest:end - 1])
src = tmpl.format(args=arg_strs, rest=rest)
tokens[start:end] = [Token('CODE', src)]
示例15: indent
# 需要导入模块: import ast [as 别名]
# 或者: from ast import List [as 别名]
def indent(lines, spaces=4):
"""Indent `lines` by `spaces` spaces.
Parameters
----------
lines : Union[str, List[str]]
A string or list of strings to indent
spaces : int
The number of spaces to indent `lines`
Returns
-------
indented_lines : str
"""
if isinstance(lines, str):
text = [lines]
text = '\n'.join(lines)
return textwrap.indent(text, ' ' * spaces)