當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.Lambda方法代碼示例

本文整理匯總了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 
開發者ID:moira-alert,項目名稱:worker,代碼行數:18,代碼來源:expression.py

示例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) 
開發者ID:Xython,項目名稱:YAPyPy,代碼行數:20,代碼來源:symbol_analyzer.py

示例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 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:19,代碼來源:eval.py

示例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,
                ],
            }
        ) 
開發者ID:megvii-research,項目名稱:hpman,代碼行數:25,代碼來源:test_parse_source.py

示例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) 
開發者ID:mila-iqia,項目名稱:myia,代碼行數:19,代碼來源:parser.py

示例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 
開發者ID:alexmojaki,項目名稱:executing,代碼行數:27,代碼來源:tracer.py

示例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)) 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:20,代碼來源:functions.py

示例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) 
開發者ID:devmanorg,項目名稱:fiasko_bro,代碼行數:8,代碼來源:pythonic.py

示例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) 
開發者ID:alecthomas,項目名稱:importmagic,代碼行數:31,代碼來源:symbols.py

示例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) 
開發者ID:alexmojaki,項目名稱:snoop,代碼行數:29,代碼來源:pp_module.py

示例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())])) 
開發者ID:LionelAuroux,項目名稱:pyrser,代碼行數:14,代碼來源:topython.py

示例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 
開發者ID:ufora,項目名稱:ufora,代碼行數:9,代碼來源:NodeVisitorBases.py

示例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) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:9,代碼來源:test_ast.py

示例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) 
開發者ID:Parquery,項目名稱:icontract,代碼行數:12,代碼來源:_represent.py

示例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) 
開發者ID:Parquery,項目名稱:icontract,代碼行數:35,代碼來源:_represent.py


注:本文中的ast.Lambda方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。