本文整理汇总了Python中ast.Lambda方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Lambda方法的具体用法?Python ast.Lambda怎么用?Python ast.Lambda使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.Lambda方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compile_expression
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def compile_expression(exp):
cached = cache.get(exp)
if cached is not None:
return cached
_exp = ast.parse(exp)
nodes = [node for node in ast.walk(_exp)]
if len(nodes) < 2 or not isinstance(nodes[1], ast.Expr):
raise ExpressionError("%s is not Expression" % exp)
for node in nodes:
if isinstance(node, ast.Call):
raise ExpressionError("Call method is forbidden")
if isinstance(node, ast.Lambda):
raise ExpressionError("Lambda is strongly forbidden")
result = compile(exp, '<string>', mode='eval')
cache[exp] = result
return result
示例2: _visit_lam
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def _visit_lam(self: 'ASTTagger', node: ast.Lambda):
args = node.args
new = self.symtable.enter_new()
arguments = args.args + args.kwonlyargs
if args.vararg:
arguments.append(args.vararg)
if args.kwarg:
arguments.append(args.kwarg)
for arg in arguments:
# lambda might be able to annotated in the future?
annotation = arg.annotation
if annotation:
self.visit(annotation)
new.entered.add(arg.arg)
new_tagger = ASTTagger(new)
node.body = new_tagger.visit(node.body)
return Tag(node, new)
示例3: ast_names
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def ast_names(code):
"""Iterator that yields all the (ast) names in a Python expression.
:arg code: A string containing a Python expression.
"""
# Syntax that allows new name bindings to be introduced is tricky to
# handle here, so we just refuse to do so.
disallowed_ast_nodes = (ast.Lambda, ast.ListComp, ast.GeneratorExp)
if sys.version_info >= (2, 7):
disallowed_ast_nodes += (ast.DictComp, ast.SetComp)
for node in ast.walk(ast.parse(code)):
if isinstance(node, disallowed_ast_nodes):
raise PatsyError("Lambda, list/dict/set comprehension, generator "
"expression in patsy formula not currently supported.")
if isinstance(node, ast.Name):
yield node.id
示例4: test_parse_type_with_func
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def test_parse_type_with_func(self):
self._run(
{
"_('hp_func', print)": [
"hp_func",
hpman.NotLiteralEvaluable(),
ast.Name,
],
"_('hp_lambda', lambda x: x)": [
"hp_lambda",
hpman.NotLiteralEvaluable(),
ast.Lambda,
],
"def foo():\n"
" pass\n"
"_('hp_def', foo)": ["hp_def", hpman.NotLiteralEvaluable(), ast.Name],
"_('hp_call', bytes('abc'))": [
"hp_call",
hpman.NotLiteralEvaluable(),
ast.Call,
],
}
)
示例5: process_Lambda
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def process_Lambda(self, block: "Block", node: ast.Lambda) -> ANFNode:
"""Process lambda: `lambda x, y: x + y`."""
function_block = self.new_block()
function_block.preds.append(block)
function_block.mature()
for arg in node.args.args:
with DebugInherit(ast=arg, location=self.make_location(arg)):
anf_node = Parameter(function_block.graph)
anf_node.debug.name = arg.arg
function_block.add_parameter(anf_node)
function_block.write(arg.arg, anf_node)
function_block.graph.output = self.process_node(
function_block, node.body
)
return Constant(function_block.graph)
示例6: _main_frame
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def _main_frame(self, node):
# type: (ast.AST) -> Optional[FrameType]
frame = sys._getframe(2)
result = self.secondary_to_main_frames.get(frame)
if result:
return result
original_frame = frame
while frame.f_code.co_name in ('<listcomp>', '<dictcomp>', '<setcomp>'):
frame = frame.f_back
for node in ancestors(node):
if isinstance(node, (ast.FunctionDef, ast.Lambda)):
break
if isinstance(node, ast.ClassDef):
frame = frame.f_back
if frame.f_code.co_name in ('<lambda>', '<genexpr>'):
return None
self.secondary_to_main_frames[original_frame] = frame
self.main_to_secondary_frames[frame].append(original_frame)
return frame
示例7: _check_useless_lambda
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def _check_useless_lambda(self, node: ast.Lambda) -> None:
if not isinstance(node.body, ast.Call):
return
if not isinstance(node.body.func, ast.Name):
# We do not track method (attr) calls, since it might me complex.
return
if node.args.defaults or list(filter(None, node.args.kw_defaults)):
# It means that `lambda` has defaults in args,
# we cannot be sure that these defaults are the same
# as in the call def, ignoring it.
# `kw_defaults` can have [None, ...] items.
return
if not function_args.is_call_matched_by_arguments(node, node.body):
return
self.add_violation(UselessLambdaViolation(node))
示例8: variable_assignment_with_lambda
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def variable_assignment_with_lambda(project_folder, *args, **kwargs):
for parsed_file in project_folder.get_parsed_py_files():
assigns = ast_helpers.get_nodes_of_type(parsed_file.ast_tree, ast.Assign)
for assign in assigns:
if isinstance(assign.value, ast.Lambda):
return '{}:{}'.format(parsed_file.name, assign.lineno)
示例9: visit_Lambda
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def visit_Lambda(self, node):
for decorator in getattr(node, 'decorator_list', []):
with self._scope.start_reference() as scope:
self.visit(decorator)
with self._scope.enter() as scope:
with scope.start_definition():
args = node.args
for arg in [args.kwarg, args.vararg]:
if arg:
# arg is either an "arg" object (Python 3.4+) or a str
scope.define(arg.arg if hasattr(arg, 'arg') else arg)
# kwonlyargs was added in Python 3
for arg in args.args + getattr(args, 'kwonlyargs', []):
scope.define(arg.id if hasattr(arg, 'id') else arg.arg)
# Python 3 arguments annotation
if hasattr(arg, 'annotation') and arg.annotation:
self.visit(arg.annotation)
for default in args.defaults:
self.visit(default)
# Python 3 return annotation
if hasattr(node, 'returns'):
self.visit(node.returns)
body = [node.body] if isinstance(node, ast.Lambda) else node.body
with scope.start_reference():
for statement in body:
self.visit(statement)
示例10: __init__
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def __init__(self, pp_object, args, deep):
self.config = pp_object.config
self.args = args
depth = getattr(self.config.thread_local, 'depth', 0)
frame = inspect.currentframe().f_back.f_back
self.event = Event(FrameInfo(frame), 'log', None, depth)
formatted = self.config.formatter.format_log(self.event)
self.config.write(formatted)
self.returns = None
try:
assert not NO_ASTTOKENS
self.call = call = Source.executing(frame).node
assert isinstance(call, ast.Call)
assert len(args) == len(call.args)
except Exception:
if deep:
self.returns = args[0] = args[0]()
for i, arg in enumerate(args):
self.write_placeholder(i, arg)
else:
if deep:
call_arg = only(call.args)
assert isinstance(call_arg, ast.Lambda), "You must pass a lambda DIRECTLY to pp.deep, not as a result of any other expression"
self.returns = self.deep_pp(call_arg.body, frame)
else:
self.plain_pp(args, call.args)
示例11: visit_CallTrue
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def visit_CallTrue(self, node: parsing.CallTrue) -> ast.expr:
"""Generates python code calling the function and returning True.
lambda: fn(*args) or True
"""
return ast.Lambda(
ast.arguments([], None, None, [], None, None, [], []),
ast.BoolOp(
ast.Or(),
[
self.visit_Call(node),
ast.Name('True', ast.Load())]))
示例12: isScopeNode
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def isScopeNode(pyAstNode):
"""Return true iff argument is a scoped node."""
if isinstance(pyAstNode, (ast.Module, ast.ClassDef,
ast.FunctionDef, ast.Lambda, ast.GeneratorExp)):
return True
else:
return False
示例13: test_lambda
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def test_lambda(self):
a = ast.arguments([], None, [], [], None, [])
self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
"must have Load context")
def fac(args):
return ast.Lambda(args, ast.Name("x", ast.Load()))
self._check_arguments(fac, self.expr)
示例14: __init__
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def __init__(self, atok: asttokens.ASTTokens, node: ast.Lambda) -> None:
"""
Initialize.
:param atok: parsed AST tree and tokens with added positional properties
:param node: lambda AST node corresponding to the condition
"""
self.atok = atok
self.node = node
self.text = atok.get_text(node.body)
示例15: find_lambda_condition
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Lambda [as 别名]
def find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]:
"""
Inspect the decorator and extract the condition as lambda.
If the condition is not given as a lambda function, return None.
"""
call_node = decorator_inspection.node
lambda_node = None # type: Optional[ast.Lambda]
if len(call_node.args) > 0:
assert isinstance(call_node.args[0], ast.Lambda), \
("Expected the first argument to the decorator to be a condition as lambda AST node, "
"but got: {}").format(type(call_node.args[0]))
lambda_node = call_node.args[0]
elif len(call_node.keywords) > 0:
for keyword in call_node.keywords:
if keyword.arg == "condition":
assert isinstance(keyword.value, ast.Lambda), \
"Expected lambda node as value of the 'condition' argument to the decorator."
lambda_node = keyword.value
break
assert lambda_node is not None, "Expected to find a keyword AST node with 'condition' arg, but found none"
else:
raise AssertionError(
"Expected a call AST node of a decorator to have either args or keywords, but got: {}".format(
ast.dump(call_node)))
return ConditionLambdaInspection(atok=decorator_inspection.atok, node=lambda_node)