Python ast.Call() Examples

The following are 30 code examples of ast.Call(). 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: Recording.py    From swirlypy with GNU General Public License v3.0 8 votes vote down vote up
def visit_Expr(self, node):
        newnode = ast.copy_location(ast.Expr(
                value = ast.Call(
                    func = ast.Attribute(
                        value = ast.Name(id='__swirlypy_recorder__',
                                    ctx=ast.Load()),
                                    attr="record",
                                    ctx=ast.Load()),
                                    args=[node.value],
                                    keywords=[],
                                    starargs=None,
                                    kwargs=None
                        )
                    ),
                node)
        ast.fix_missing_locations(newnode)
        return newnode 
Example #2
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 #3
Source File: upgrade_stdmodule.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def pre_Assign(self):
        value = self.cur_node.value
        for target in self.cur_node.targets:
            # ignore Subscripts for now
            if isinstance(target, _ast.Name):
                if target.id == '_target_model':
                    assert(isinstance(value, _ast.Call))
                    # done in three separate phases for safety with stringly-typed arguments
                    StateSpaceLabelWalker(value.args[0])
                    LabelWalker(value.args[1])
                    ExpressionWalker(value.args[2])
                else:
                    LabelWalker(value)

                # Build dependencies from the rhs
                # We don't consider the function name a dependency so bypass that
                critical_ast = value.args if isinstance(value, _ast.Call) else value
                value._dependencies = DependencyWalker(critical_ast).dependencies
                self.upgrades[target.id] = value

        return False


# Build variables for filling in the template 
Example #4
Source File: expr.py    From recruit with Apache License 2.0 6 votes vote down vote up
def visit_BoolOp(self, node, **kwargs):
        def visitor(x, y):
            lhs = self._try_visit_binop(x)
            rhs = self._try_visit_binop(y)

            op, op_class, lhs, rhs = self._maybe_transform_eq_ne(
                node, lhs, rhs)
            return self._maybe_evaluate_binop(op, node.op, lhs, rhs)

        operands = node.values
        return reduce(visitor, operands)


# ast.Call signature changed on 3.5,
# conditionally change which methods is named
# visit_Call depending on Python version, #11097 
Example #5
Source File: action.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def visit_With(self, node):
        parallel_tasks = []
        if len(node.items) > 1:
            raise ValueError(
                "Only a single context is supported in 'with' statements inside the action."
            )
        context = eval(
            compile(ast.Expression(node.items[0].context_expr), "", "eval"),
            self._globals,
        )
        if context.__calm_type__ == "parallel":
            for statement in node.body:
                if not isinstance(statement.value, ast.Call):
                    raise ValueError(
                        "Only calls to 'CalmTask' methods supported inside parallel context."
                    )
                task = self.visit_Call(statement.value, return_task=True)
                if task:
                    parallel_tasks.append(task)
                    self.all_tasks.append(task)
            self.task_list.append(parallel_tasks)
        else:
            raise ValueError(
                "Unsupported context used in 'with' statement inside the action."
            ) 
Example #6
Source File: setup_reader.py    From poetry with MIT License 6 votes vote down vote up
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 
Example #7
Source File: transformers.py    From async2rewrite with MIT License 6 votes vote down vote up
def ensure_ctx_var(self, coro):

        d_list = []
        for d in coro.decorator_list:
            if isinstance(d, ast.Attribute):
                d_list.append(d.attr)
            elif isinstance(d, ast.Call):
                if isinstance(d.func, ast.Attribute):
                    d_list.append(d.func.attr)
        if 'command' not in d_list:
            return coro

        coro_args = [arg.arg for arg in coro.args.args]

        if not coro_args:
            coro.args.args.append(ast.arg(arg='ctx', annotation=None))
        elif 'self' in coro_args and 'ctx' not in coro_args:
            coro.args.args.insert(1, ast.arg(arg='ctx', annotation=None))
        elif 'self' not in coro_args and 'ctx' not in coro_args:
            coro.args.args.insert(0, ast.arg(arg='ctx', annotation=None))

        stats_counter['coro_changes'] += 1

        return coro 
Example #8
Source File: _ast_to_ir2.py    From tmppy with Apache License 2.0 6 votes vote down vote up
def _extract_single_type_expr_arg(ast_node: ast.Call,
                                  called_fun_name: str,
                                  compilation_context: CompilationContext,
                                  in_match_pattern: bool,
                                  check_var_reference: Callable[[ast.Name], None],
                                  match_lambda_argument_names: Set[str],
                                  current_stmt_line: int):
    if ast_node.keywords:
        raise CompilationError(compilation_context, ast_node.keywords[0].value,
                               'Keyword arguments are not supported in %s()' % called_fun_name)

    if len(ast_node.args) != 1:
        raise CompilationError(compilation_context, ast_node, '%s() takes 1 argument. Got: %s' % (called_fun_name, len(ast_node.args)))
    [arg] = ast_node.args

    arg_ir = expression_ast_to_ir2(arg,
                                   compilation_context,
                                   in_match_pattern,
                                   check_var_reference,
                                   match_lambda_argument_names,
                                   current_stmt_line)
    if arg_ir.expr_type != ir2.TypeType():
        raise CompilationError(compilation_context, arg, 'The argument passed to %s() should have type Type, but was: %s' % (called_fun_name, str(arg_ir.expr_type)))
    return arg_ir 
Example #9
Source File: asttools.py    From sspam with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def visit_BinOp(self, node):
        'Replace bitwise operation with function call'
        self.generic_visit(node)
        if isinstance(node.op, ast.BitAnd):
            return ast.Call(ast.Name('mand', ast.Load()),
                            [node.left, node.right], [], None, None)
        if isinstance(node.op, ast.BitOr):
            return ast.Call(ast.Name('mor', ast.Load()),
                            [node.left, node.right], [], None, None)
        if isinstance(node.op, ast.BitXor):
            return ast.Call(ast.Name('mxor', ast.Load()),
                            [node.left, node.right], [], None, None)
        if isinstance(node.op, ast.LShift):
            return ast.Call(ast.Name('mlshift', ast.Load()),
                            [node.left, node.right], [], None, None)
        if isinstance(node.op, ast.RShift):
            return ast.Call(ast.Name('mrshift', ast.Load()),
                            [node.left, node.right], [], None, None)
        return node 
Example #10
Source File: cmd.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
def _apply_imports_to_unparsed_expression(exp_ast, imports):
  """Attempts to evaluate the code equivalent of `exp_ast`, with `imports`
  as available symbols. If it's successful, it returns the evaluated object.
  Otherwise this returns the unparsed code for `exp_ast`.

  Args:
    * exp_ast (Union[ast.Name, ast.Attribute, ast.Call]) - The expression to
      evaluate.
    * imports (Dict[str, object]) - The symbols to include during the evaluation
      of `exp_ast`.

  Returns the evaluation of `exp_ast` if it can successfully evaluate with
  `imports`. Otherwise this returns the source-code representation of exp_ast as
  a string.
  """
  assert isinstance(exp_ast, (ast.Name, ast.Attribute, ast.Call)), type(exp_ast)
  unparsed = _unparse(exp_ast).strip()
  try:
    return eval(unparsed, {'__builtins__': None}, imports)
  except (NameError, AttributeError):
    return unparsed 
Example #11
Source File: _ast_to_ir2.py    From tmppy with Apache License 2.0 6 votes vote down vote up
def atomic_type_literal_ast_to_ir2(ast_node: ast.Call,
                                   compilation_context: CompilationContext,
                                   in_match_pattern: bool,
                                   check_var_reference: Callable[[ast.Name], None],
                                   match_lambda_argument_names: Set[str]):
    if ast_node.keywords:
        raise CompilationError(compilation_context, ast_node.keywords[0].value,
                               'Keyword arguments are not supported in Type()')

    if len(ast_node.args) != 1:
        raise CompilationError(compilation_context, ast_node, 'Type() takes 1 argument. Got: %s' % len(ast_node.args))
    [arg] = ast_node.args
    if not isinstance(arg, ast.Str):
        raise CompilationError(compilation_context, arg, 'The argument passed to Type should be a string constant.')
    _check_atomic_type(arg, compilation_context)
    return ir2.AtomicTypeLiteral(cpp_type=arg.s) 
Example #12
Source File: test_ast.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_dump(self):
        node = ast.parse('spam(eggs, "and cheese")')
        self.assertEqual(ast.dump(node),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
            "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
            "keywords=[], starargs=None, kwargs=None))])"
        )
        self.assertEqual(ast.dump(node, annotate_fields=False),
            "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
            "Str('and cheese')], [], None, None))])"
        )
        self.assertEqual(ast.dump(node, include_attributes=True),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
            "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
            "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
            "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
            "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
        ) 
Example #13
Source File: checker.py    From linter-pylama with MIT License 6 votes vote down vote up
def NAME(self, node):
        """
        Handle occurrence of Name (which can be a load/store/delete access.)
        """
        # Locate the name in locals / function / globals scopes.
        if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
            self.handleNodeLoad(node)
            if (node.id == 'locals' and isinstance(self.scope, FunctionScope)
                    and isinstance(node.parent, ast.Call)):
                # we are doing locals() call in current scope
                self.scope.usesLocals = True
        elif isinstance(node.ctx, (ast.Store, ast.AugStore)):
            self.handleNodeStore(node)
        elif isinstance(node.ctx, ast.Del):
            self.handleNodeDelete(node)
        else:
            # must be a Param context -- this only happens for names in function
            # arguments, but these aren't dispatched through here
            raise RuntimeError("Got impossible expression context: %r" % (node.ctx,)) 
Example #14
Source File: _analyze.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_For(self, node):
        node.breakLabel = _Label("BREAK")
        node.loopLabel = _Label("LOOP")
        self.labelStack.append(node.breakLabel)
        self.labelStack.append(node.loopLabel)
        self.refStack.push()
        self.visit(node.target)
        var = node.target.id
        self.tree.vardict[var] = int(-1)

        cf = node.iter
        self.visit(cf)
        self.require(node, isinstance(cf, ast.Call), "Expected (down)range call")
        f = self.getObj(cf.func)
        self.require(node, f in (range, downrange), "Expected (down)range call")

        for stmt in node.body:
            self.visit(stmt)
        self.refStack.pop()
        self.require(node, not node.orelse, "for-else not supported")
        self.labelStack.pop()
        self.labelStack.pop() 
Example #15
Source File: readers.py    From pdm with MIT License 6 votes vote down vote up
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 
Example #16
Source File: rewrite.py    From python-netsurv with MIT License 5 votes vote down vote up
def visit_Call(self, call):
        """
        visit `ast.Call` nodes
        """
        new_func, func_expl = self.visit(call.func)
        arg_expls = []
        new_args = []
        new_kwargs = []
        for arg in call.args:
            res, expl = self.visit(arg)
            arg_expls.append(expl)
            new_args.append(res)
        for keyword in call.keywords:
            res, expl = self.visit(keyword.value)
            new_kwargs.append(ast.keyword(keyword.arg, res))
            if keyword.arg:
                arg_expls.append(keyword.arg + "=" + expl)
            else:  # **args have `arg` keywords with an .arg of None
                arg_expls.append("**" + expl)

        expl = "{}({})".format(func_expl, ", ".join(arg_expls))
        new_call = ast.Call(new_func, new_args, new_kwargs)
        res = self.assign(new_call)
        res_expl = self.explanation_param(self.display(res))
        outer_expl = "{}\n{{{} = {}\n}}".format(res_expl, res_expl, expl)
        return res, outer_expl 
Example #17
Source File: setup_reader.py    From poetry with MIT License 5 votes vote down vote up
def _find_call_kwargs(self, call):  # type: (ast.Call) -> Optional[Any]
        kwargs = None
        for keyword in call.keywords:
            if keyword.arg is None:
                kwargs = keyword.value

        return kwargs 
Example #18
Source File: _ast_to_ir2.py    From tmppy with Apache License 2.0 5 votes vote down vote up
def bool_iterable_all_expr_ast_to_ir2(ast_node: ast.Call,
                                      compilation_context: CompilationContext,
                                      in_match_pattern: bool,
                                      check_var_reference: Callable[[ast.Name], None],
                                      current_stmt_line: int):
    if in_match_pattern:
        raise CompilationError(compilation_context, ast_node,
                               'all() is not allowed in match patterns')

    if ast_node.keywords:
        raise CompilationError(compilation_context, ast_node.keywords[0].value, 'Keyword arguments are not supported.')
    if len(ast_node.args) != 1:
        raise CompilationError(compilation_context, ast_node, 'all() takes 1 argument. Got: %s' % len(ast_node.args))
    [arg] = ast_node.args
    arg_expr = expression_ast_to_ir2(arg,
                                     compilation_context,
                                     in_match_pattern,
                                     check_var_reference,
                                     match_lambda_argument_names=set(),
                                     current_stmt_line=current_stmt_line)
    if not (isinstance(arg_expr.expr_type, (ir2.ListType, ir2.SetType)) and isinstance(arg_expr.expr_type.elem_type, ir2.BoolType)):
        notes = []
        if isinstance(arg_expr, ir2.VarReference):
            lookup_result = compilation_context.get_symbol_definition(arg_expr.name)
            assert lookup_result
            assert not lookup_result.is_only_partially_defined
            notes.append((lookup_result.ast_node, '%s was defined here' % arg_expr.name))
        raise CompilationError(compilation_context, arg,
                               'The argument of all() must have type List[bool] or Set[bool]. Got type: %s' % str(arg_expr.expr_type),
                               notes=notes)
    if isinstance(arg_expr.expr_type, ir2.ListType):
        return ir2.BoolListAllExpr(list_expr=arg_expr)
    else:
        return ir2.BoolSetAllExpr(set_expr=arg_expr) 
Example #19
Source File: _ast_to_ir2.py    From tmppy with Apache License 2.0 5 votes vote down vote up
def bool_iterable_any_expr_ast_to_ir2(ast_node: ast.Call,
                                      compilation_context: CompilationContext,
                                      in_match_pattern: bool,
                                      check_var_reference: Callable[[ast.Name], None],
                                      current_stmt_line: int):
    if in_match_pattern:
        raise CompilationError(compilation_context, ast_node,
                               'any() is not allowed in match patterns')

    if ast_node.keywords:
        raise CompilationError(compilation_context, ast_node.keywords[0].value, 'Keyword arguments are not supported.')
    if len(ast_node.args) != 1:
        raise CompilationError(compilation_context, ast_node, 'any() takes 1 argument. Got: %s' % len(ast_node.args))
    [arg] = ast_node.args
    arg_expr = expression_ast_to_ir2(arg,
                                     compilation_context,
                                     in_match_pattern,
                                     check_var_reference,
                                     match_lambda_argument_names=set(),
                                     current_stmt_line=current_stmt_line)
    if not (isinstance(arg_expr.expr_type, (ir2.ListType, ir2.SetType)) and isinstance(arg_expr.expr_type.elem_type, ir2.BoolType)):
        notes = []
        if isinstance(arg_expr, ir2.VarReference):
            lookup_result = compilation_context.get_symbol_definition(arg_expr.name)
            assert lookup_result
            assert not lookup_result.is_only_partially_defined
            notes.append((lookup_result.ast_node, '%s was defined here' % arg_expr.name))
        raise CompilationError(compilation_context, arg,
                               'The argument of any() must have type List[bool] or Set[bool]. Got type: %s' % str(arg_expr.expr_type),
                               notes=notes)
    if isinstance(arg_expr.expr_type, ir2.ListType):
        return ir2.BoolListAnyExpr(list_expr=arg_expr)
    else:
        return ir2.BoolSetAnyExpr(set_expr=arg_expr) 
Example #20
Source File: test_ast.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_fix_missing_locations(self):
        src = ast.parse('write("spam")')
        src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
                                          [ast.Str('eggs')], [], None, None)))
        self.assertEqual(src, ast.fix_missing_locations(src))
        self.assertEqual(ast.dump(src, include_attributes=True),
            "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
            "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, "
            "col_offset=6)], keywords=[], starargs=None, kwargs=None, "
            "lineno=1, col_offset=0), lineno=1, col_offset=0), "
            "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
            "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], "
            "keywords=[], starargs=None, kwargs=None, lineno=1, "
            "col_offset=0), lineno=1, col_offset=0)])"
        ) 
Example #21
Source File: setup_reader.py    From poetry with MIT License 5 votes vote down vote up
def _find_single_string(
        self, call, body, name
    ):  # type: (ast.Call, List[Any], str) -> Optional[str]
        value = self._find_in_call(call, name)
        if value is None:
            # Trying to find in kwargs
            kwargs = self._find_call_kwargs(call)

            if kwargs is None or not isinstance(kwargs, ast.Name):
                return

            variable = self._find_variable_in_body(body, kwargs.id)
            if not isinstance(variable, (ast.Dict, ast.Call)):
                return

            if isinstance(variable, ast.Call):
                if not isinstance(variable.func, ast.Name):
                    return

                if variable.func.id != "dict":
                    return

                value = self._find_in_call(variable, name)
            else:
                value = self._find_in_dict(variable, name)

        if value is None:
            return

        if isinstance(value, ast.Str):
            return value.s
        elif isinstance(value, ast.Name):
            variable = self._find_variable_in_body(body, value.id)

            if variable is not None and isinstance(variable, ast.Str):
                return variable.s 
Example #22
Source File: setup_reader.py    From poetry with MIT License 5 votes vote down vote up
def _find_install_requires(
        self, call, body
    ):  # type: (ast.Call, Iterable[Any]) -> List[str]
        install_requires = []
        value = self._find_in_call(call, "install_requires")
        if value is None:
            # Trying to find in kwargs
            kwargs = self._find_call_kwargs(call)

            if kwargs is None or not isinstance(kwargs, ast.Name):
                return install_requires

            variable = self._find_variable_in_body(body, kwargs.id)
            if not isinstance(variable, (ast.Dict, ast.Call)):
                return install_requires

            if isinstance(variable, ast.Call):
                if not isinstance(variable.func, ast.Name):
                    return install_requires

                if variable.func.id != "dict":
                    return install_requires

                value = self._find_in_call(variable, "install_requires")
            else:
                value = self._find_in_dict(variable, "install_requires")

        if value is None:
            return install_requires

        if isinstance(value, ast.List):
            for el in value.elts:
                install_requires.append(el.s)
        elif isinstance(value, ast.Name):
            variable = self._find_variable_in_body(body, value.id)

            if variable is not None and isinstance(variable, ast.List):
                for el in variable.elts:
                    install_requires.append(el.s)

        return install_requires 
Example #23
Source File: _ast_to_ir2.py    From tmppy with Apache License 2.0 5 votes vote down vote up
def type_reference_expr_ast_to_ir2(ast_node: ast.Call,
                                   compilation_context: CompilationContext,
                                   in_match_pattern: bool,
                                   check_var_reference: Callable[[ast.Name], None],
                                   match_lambda_argument_names: Set[str],
                                   current_stmt_line: int):
    return ir2.ReferenceTypeExpr(_extract_single_type_expr_arg(ast_node,
                                                               'Type.reference',
                                                               compilation_context,
                                                               in_match_pattern,
                                                               check_var_reference,
                                                               match_lambda_argument_names,
                                                               current_stmt_line)) 
Example #24
Source File: rewrite.py    From python-netsurv with MIT License 5 votes vote down vote up
def visit_BoolOp(self, boolop):
        res_var = self.variable()
        expl_list = self.assign(ast.List([], ast.Load()))
        app = ast.Attribute(expl_list, "append", ast.Load())
        is_or = int(isinstance(boolop.op, ast.Or))
        body = save = self.statements
        fail_save = self.expl_stmts
        levels = len(boolop.values) - 1
        self.push_format_context()
        # Process each operand, short-circuiting if needed.
        for i, v in enumerate(boolop.values):
            if i:
                fail_inner = []
                # cond is set in a prior loop iteration below
                self.expl_stmts.append(ast.If(cond, fail_inner, []))  # noqa
                self.expl_stmts = fail_inner
            self.push_format_context()
            res, expl = self.visit(v)
            body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
            expl_format = self.pop_format_context(ast.Str(expl))
            call = ast.Call(app, [expl_format], [])
            self.expl_stmts.append(ast.Expr(call))
            if i < levels:
                cond = res
                if is_or:
                    cond = ast.UnaryOp(ast.Not(), cond)
                inner = []
                self.statements.append(ast.If(cond, inner, []))
                self.statements = body = inner
        self.statements = save
        self.expl_stmts = fail_save
        expl_template = self.helper("_format_boolop", expl_list, ast.Num(is_or))
        expl = self.pop_format_context(expl_template)
        return ast.Name(res_var, ast.Load()), self.explanation_param(expl) 
Example #25
Source File: rewrite.py    From python-netsurv with MIT License 5 votes vote down vote up
def visit_Name(self, name):
        # Display the repr of the name if it's a local variable or
        # _should_repr_global_name() thinks it's acceptable.
        locs = ast.Call(self.builtin("locals"), [], [])
        inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])
        dorepr = self.helper("_should_repr_global_name", name)
        test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
        expr = ast.IfExp(test, self.display(name), ast.Str(name.id))
        return name, self.explanation_param(expr) 
Example #26
Source File: rewrite.py    From python-netsurv with MIT License 5 votes vote down vote up
def helper(self, name, *args):
        """Call a helper in this module."""
        py_name = ast.Name("@pytest_ar", ast.Load())
        attr = ast.Attribute(py_name, name, ast.Load())
        return ast.Call(attr, list(args), []) 
Example #27
Source File: rewrite.py    From python-netsurv with MIT License 5 votes vote down vote up
def visit_Call(self, call):
        """
        visit `ast.Call` nodes
        """
        new_func, func_expl = self.visit(call.func)
        arg_expls = []
        new_args = []
        new_kwargs = []
        for arg in call.args:
            res, expl = self.visit(arg)
            arg_expls.append(expl)
            new_args.append(res)
        for keyword in call.keywords:
            res, expl = self.visit(keyword.value)
            new_kwargs.append(ast.keyword(keyword.arg, res))
            if keyword.arg:
                arg_expls.append(keyword.arg + "=" + expl)
            else:  # **args have `arg` keywords with an .arg of None
                arg_expls.append("**" + expl)

        expl = "{}({})".format(func_expl, ", ".join(arg_expls))
        new_call = ast.Call(new_func, new_args, new_kwargs)
        res = self.assign(new_call)
        res_expl = self.explanation_param(self.display(res))
        outer_expl = "{}\n{{{} = {}\n}}".format(res_expl, res_expl, expl)
        return res, outer_expl 
Example #28
Source File: rewrite.py    From python-netsurv with MIT License 5 votes vote down vote up
def visit_BoolOp(self, boolop):
        res_var = self.variable()
        expl_list = self.assign(ast.List([], ast.Load()))
        app = ast.Attribute(expl_list, "append", ast.Load())
        is_or = int(isinstance(boolop.op, ast.Or))
        body = save = self.statements
        fail_save = self.expl_stmts
        levels = len(boolop.values) - 1
        self.push_format_context()
        # Process each operand, short-circuiting if needed.
        for i, v in enumerate(boolop.values):
            if i:
                fail_inner = []
                # cond is set in a prior loop iteration below
                self.expl_stmts.append(ast.If(cond, fail_inner, []))  # noqa
                self.expl_stmts = fail_inner
            self.push_format_context()
            res, expl = self.visit(v)
            body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
            expl_format = self.pop_format_context(ast.Str(expl))
            call = ast.Call(app, [expl_format], [])
            self.expl_stmts.append(ast.Expr(call))
            if i < levels:
                cond = res
                if is_or:
                    cond = ast.UnaryOp(ast.Not(), cond)
                inner = []
                self.statements.append(ast.If(cond, inner, []))
                self.statements = body = inner
        self.statements = save
        self.expl_stmts = fail_save
        expl_template = self.helper("_format_boolop", expl_list, ast.Num(is_or))
        expl = self.pop_format_context(expl_template)
        return ast.Name(res_var, ast.Load()), self.explanation_param(expl) 
Example #29
Source File: rewrite.py    From python-netsurv with MIT License 5 votes vote down vote up
def visit_Name(self, name):
        # Display the repr of the name if it's a local variable or
        # _should_repr_global_name() thinks it's acceptable.
        locs = ast.Call(self.builtin("locals"), [], [])
        inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])
        dorepr = self.helper("_should_repr_global_name", name)
        test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
        expr = ast.IfExp(test, self.display(name), ast.Str(name.id))
        return name, self.explanation_param(expr) 
Example #30
Source File: rewrite.py    From python-netsurv with MIT License 5 votes vote down vote up
def helper(self, name, *args):
        """Call a helper in this module."""
        py_name = ast.Name("@pytest_ar", ast.Load())
        attr = ast.Attribute(py_name, name, ast.Load())
        return ast.Call(attr, list(args), [])