Python ast.Lambda() Examples

The following are 30 code examples of ast.Lambda(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: expression.py    From worker with GNU General Public License v3.0 7 votes vote down vote up
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 
Example #2
Source File: symbol_analyzer.py    From YAPyPy with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: eval.py    From vnpy_crypto with MIT License 6 votes vote down vote up
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 
Example #4
Source File: eval.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: tracer.py    From executing with MIT License 6 votes vote down vote up
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 
Example #6
Source File: test_parse_source.py    From hpman with MIT License 6 votes vote down vote up
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,
                ],
            }
        ) 
Example #7
Source File: functions.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
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)) 
Example #8
Source File: parser.py    From myia with MIT License 6 votes vote down vote up
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) 
Example #9
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_lambdef_1(p):
    '''lambdef : LAMBDA COLON test'''
    #                 1     2    3
    p[0] = ast.Lambda(ast.arguments([], None, None, [], rule=inspect.currentframe().f_code.co_name, **p[2][1]), p[3], rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #10
Source File: pythonic.py    From fiasko_bro with MIT License 5 votes vote down vote up
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) 
Example #11
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_lambdef_2(p):
    '''lambdef : LAMBDA varargslist COLON test'''
    #                 1           2     3    4
    p[0] = ast.Lambda(p[2], p[4], rule=inspect.currentframe().f_code.co_name, **p[1][1])

# trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME 
Example #12
Source File: hgawk_test.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def functionalize(node):
    # changes node in-place, but returns it anyway
    if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
        for i, x in enumerate(node.args):
            if (node.func.id, i) in expectFunction:
                numargs = highestDollar(x)
                if numargs > 0:
                    # the parameter name "$args" can't conflict with any valid Python names
                    out = ast.Lambda(ast.arguments([ast.Name("$args", ast.Param())], None, None, []), dollarToArg(x))
                    out.lineno,                  out.col_offset                  = x.lineno, x.col_offset
                    out.args.lineno,             out.args.col_offset             = x.lineno, x.col_offset
                    out.args.args[0].lineno,     out.args.args[0].col_offset     = x.lineno, x.col_offset
                    out.args.args[0].ctx.lineno, out.args.args[0].ctx.col_offset = x.lineno, x.col_offset
                    node.args[i] = out

        for keyword in node.keywords:
            if (node.func.id, keyword.arg) in expectFunction:
                x = keyword.value
                numargs = highestDollar(x)
                if numargs > 0:
                    out = ast.Lambda(ast.arguments([ast.Name("$args", ast.Param())], None, None, []), dollarToArg(x))
                    out.lineno,                  out.col_offset                  = x.lineno, x.col_offset
                    out.args.lineno,             out.args.col_offset             = x.lineno, x.col_offset
                    out.args.args[0].lineno,     out.args.args[0].col_offset     = x.lineno, x.col_offset
                    out.args.args[0].ctx.lineno, out.args.args[0].ctx.col_offset = x.lineno, x.col_offset
                    keyword.value = out
                    
    for field in node._fields:
        subnode = getattr(node, field)
        if isinstance(subnode, ast.AST):
            functionalize(subnode)
        elif isinstance(subnode, list):
            for x in subnode:
                if isinstance(x, ast.AST):
                    functionalize(x)

    return node 
Example #13
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #14
Source File: check_funcs.py    From pythonwhat with GNU Affero General Public License v3.0 5 votes vote down vote up
def build_call(callstr, node):
    if isinstance(node, ast.FunctionDef):  # function name
        func_expr = ast.Name(id=node.name, ctx=ast.Load())
        argstr = "`%s`" % callstr.replace("f", node.name)
    elif isinstance(node, ast.Lambda):  # lambda body expr
        func_expr = node
        argstr = "it with the arguments `%s`" % callstr.replace("f", "")
    else:
        raise TypeError("Can't handle AST that is passed.")

    parsed = ast.parse(callstr).body[0].value
    parsed.func = func_expr
    ast.fix_missing_locations(parsed)
    return parsed, argstr 
Example #15
Source File: utils.py    From pythonwhat with GNU Affero General Public License v3.0 5 votes vote down vote up
def run_call(args, node, process, get_func, **kwargs):
    # Get function expression
    if isinstance(node, ast.FunctionDef):  # function name
        func_expr = ast.Name(id=node.name, ctx=ast.Load())
    elif isinstance(node, ast.Lambda):  # lambda body expr
        func_expr = node
    else:
        raise InstructorError.from_message(
            "Only function definition or lambda may be called"
        )

    ast.fix_missing_locations(func_expr)
    return get_func(process=process, tree=func_expr, call=args, **kwargs) 
Example #16
Source File: parsing.py    From pythonwhat with GNU Affero General Public License v3.0 5 votes vote down vote up
def parse_node(cls, node):
        normal_args = cls.get_arg_tuples(node.args.args, node.args.defaults)
        kwonlyargs = cls.get_arg_tuples(node.args.kwonlyargs, node.args.kw_defaults)
        # TODO: all single args should be tuples like this
        vararg = cls.get_arg(node.args.vararg)
        kwarg = cls.get_arg(node.args.kwarg)
        # create context variables
        target_vars = [arg[0] for arg in normal_args]
        if vararg:
            target_vars.append(vararg)
        if kwarg:
            target_vars.append(kwarg)

        args = cls.get_arg_parts(node.args.args, node.args.defaults, "arg")
        kw_args = cls.get_arg_parts(
            node.args.kwonlyargs, node.args.kw_defaults, "kwonly"
        )
        varargs = cls.get_arg_part(node.args.vararg, None, "vararg")
        kwargs = cls.get_arg_part(node.args.kwarg, None, "kwarg")
        all_args = [*args, varargs, *kw_args, kwargs]

        if isinstance(node, ast.Lambda):
            body_node = node.body
        else:
            bodyMod = wrap_in_module(node.body)
            body_node = FunctionBodyTransformer().visit(bodyMod)

        return {
            "node": node,
            "name": getattr(node, "name", None),
            "args": IndexedDict([(p["name"], p) for p in all_args if p is not None]),
            # TODO: arg is the node counterpart to target_vars
            "_spec1_args": args,
            "*args": varargs,
            "**kwargs": kwargs,
            "body": {"node": body_node, "target_vars": TargetVars(target_vars)},
        } 
Example #17
Source File: analyzer.py    From chalice with Apache License 2.0 5 votes vote down vote up
def visit_Lambda(self, node):
        # type: (ast.Lambda) -> None
        # Lambda is going to be a bit tricky because
        # there's a new child namespace (via .get_children()),
        # but it's not something that will show up in the
        # current symbol table via .lookup().
        # For now, we're going to ignore lambda expressions.
        pass 
Example #18
Source File: functions.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def visit_Lambda(self, node: ast.Lambda) -> None:
        """
        Checks if ``lambda`` functions are defined correctly.

        Raises:
            UselessLambdaViolation
            ImplicitPrimitiveViolation

        """
        self._check_useless_lambda(node)
        self._check_implicit_primitive(node)
        self.generic_visit(node) 
Example #19
Source File: functions.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_implicit_primitive(self, node: ast.Lambda) -> None:
        arguments = functions.get_all_arguments(node)
        if arguments:
            # We return from this check, since `lambda` has some arguments.
            return

        with suppress(ValueError):
            return_value = ast.literal_eval(node.body)
            if return_value is not None and not return_value:
                self.add_violation(ImplicitPrimitiveViolation(node)) 
Example #20
Source File: loops.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_lambda_inside_loop(
        self,
        node: Union[AnyLoop, AnyComprehension],
    ) -> None:
        container_names = self._containers.get(type(node), ())
        for container in container_names:
            body = getattr(node, container, [])
            if not isinstance(body, list):
                body = [body]

            for subnode in body:
                if walk.is_contained(subnode, ast.Lambda):
                    self.add_violation(LambdaInsideLoopViolation(node)) 
Example #21
Source File: nested.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def visit_Lambda(self, node: ast.Lambda) -> None:
        """
        Used to find nested ``lambda`` functions.

        Raises:
            NestedFunctionViolation

        """
        self._check_nested_lambdas(node)
        self.generic_visit(node) 
Example #22
Source File: function.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def visit_Lambda(self, node: ast.Lambda) -> None:
        """
        Checks lambda function's internal complexity.

        Raises:
            TooManyArgumentsViolation

        """
        self._counter.check_arguments_count(node)
        self.generic_visit(node) 
Example #23
Source File: naming.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def check_function_signature(self, node: AnyFunctionDefAndLambda) -> None:
        for arg in functions.get_all_arguments(node):
            should_check_argument = (
                functions.is_first_argument(node, arg.arg) and
                not isinstance(node, ast.Lambda)
            )

            self.check_name(
                arg, arg.arg, is_first_argument=should_check_argument,
            ) 
Example #24
Source File: naming.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def visit_Lambda(self, node: ast.Lambda) -> None:
        """
        Used to find wrong parameters.

        Raises:
            WrongVariableNameViolation
            TooShortNameViolation
            PrivateNameViolation
            TooLongNameViolation
            TrailingUnderscoreViolation

        """
        self._validator.check_function_signature(node)
        self.generic_visit(node) 
Example #25
Source File: function_args.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _get_args_without_special_argument(
    node: types.AnyFunctionDefAndLambda,
) -> List[ast.arg]:
    """
    Gets ``node`` arguments excluding ``self``, ``cls``, ``mcs``.

    In ``python3.8+`` we have this case: ``def some(a, /, b): ...``
    It is ignored on all other versions.
    """
    node_args = get_posonlyargs(node) + node.args.args
    if not node_args or isinstance(node, ast.Lambda):
        return node_args
    if node_args[0].arg not in constants.SPECIAL_ARGUMENT_NAMES_WHITELIST:
        return node_args
    return node_args[1:] 
Example #26
Source File: _recompute.py    From icontract with MIT License 5 votes vote down vote up
def visit_Lambda(self, node: ast.Lambda) -> Callable[..., Any]:
        """Do not support inline lambda until there is a feature request since this is quite tricky to implement."""
        raise NotImplementedError(
            "Recomputation of in-line lambda functions is not supported since it is quite tricky to implement and "
            "we decided to implement it only once there is a real need for it. "
            "Please make a feature request on https://github.com/Parquery/icontract") 
Example #27
Source File: symbols.py    From importmagic with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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) 
Example #28
Source File: pp_module.py    From snoop with MIT License 5 votes vote down vote up
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) 
Example #29
Source File: topython.py    From pyrser with GNU General Public License v3.0 5 votes vote down vote up
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())])) 
Example #30
Source File: NodeVisitorBases.py    From ufora with Apache License 2.0 5 votes vote down vote up
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