Python ast.Return() Examples

The following are 30 code examples of ast.Return(). 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: parallel.py    From XQuant with MIT License 7 votes vote down vote up
def generic_visit(self, node):
        super(NodeTransformer, self).generic_visit(node)
        if hasattr(node, 'body') and type(node.body) is list:
            returns = [i for i, child in enumerate(node.body) if type(child) is ast.Return]
            if len(returns) > 0:
                for wait in self.get_waits():
                    node.body.insert(returns[0], wait)
            inserts = []
            for i, child in enumerate(node.body):
                if type(child) is ast.Expr and self.is_concurrent_call(child.value):
                    self.encounter_call(child.value)
                elif self.is_valid_assignment(child):
                    call = child.value
                    self.encounter_call(call)
                    name = child.targets[0].value
                    self.arguments.add(SchedulerRewriter.top_level_name(name))
                    index = child.targets[0].slice.value
                    call.func = ast.Attribute(call.func, 'assign', ast.Load())
                    call.args = [ast.Tuple([name, index], ast.Load())] + call.args
                    node.body[i] = ast.Expr(call)
                elif self.references_arg(child):
                    inserts.insert(0, i)
            for index in inserts:
                for wait in self.get_waits():
                    node.body.insert(index, wait) 
Example #2
Source File: _343.py    From codetransformer with GNU General Public License v2.0 6 votes vote down vote up
def _make_dict_elems(build_instr, builders):
    """
    Return a list of keys and a list of values for the dictionary literal
    generated by ``build_instr``.
    """
    keys = []
    values = []
    for _ in range(build_instr.arg):
        popped = builders.pop()
        if not isinstance(popped, instrs.STORE_MAP):
            raise DecompilationError(
                "Expected a STORE_MAP but got %s" % popped
            )

        keys.append(make_expr(builders))
        values.append(make_expr(builders))

    # Keys and values are emitted in reverse order of how they appear in the
    # AST.
    keys.reverse()
    values.reverse()
    return keys, values 
Example #3
Source File: parser.py    From myia with MIT License 6 votes vote down vote up
def jump(self, target: "Block", *args) -> Apply:
        """Jumping from one block to the next becomes a tail call.

        This method will generate the tail call by calling the graph
        corresponding to the target block using an `Apply` node, and returning
        its value with a `Return` node. It will update the predecessor blocks
        of the target appropriately.

        Args:
            target: The block to jump to from this statement.

        """
        assert self.graph.return_ is None
        jump = self.apply(target.graph, *args)
        jump_call = jump
        if self.use_universe:
            jump_call = jump.inputs[1]
        self.jumps[target] = jump_call
        target.preds.append(self)
        self.returns(jump) 
Example #4
Source File: sembuilder.py    From miasm with GNU General Public License v2.0 6 votes vote down vote up
def _create_labels(loc_else=False):
        """Return the AST standing for label creations
        @loc_else (optional): if set, create a label 'loc_else'"""
        loc_end = "loc_end = ir.get_next_loc_key(instr)"
        loc_end_expr = "loc_end_expr = ExprLoc(loc_end, ir.IRDst.size)"
        out = ast.parse(loc_end).body
        out += ast.parse(loc_end_expr).body
        loc_if = "loc_if = ir.loc_db.add_location()"
        loc_if_expr = "loc_if_expr = ExprLoc(loc_if, ir.IRDst.size)"
        out += ast.parse(loc_if).body
        out += ast.parse(loc_if_expr).body
        if loc_else:
            loc_else = "loc_else = ir.loc_db.add_location()"
            loc_else_expr = "loc_else_expr = ExprLoc(loc_else, ir.IRDst.size)"
            out += ast.parse(loc_else).body
            out += ast.parse(loc_else_expr).body
        return out 
Example #5
Source File: core.py    From vulture with MIT License 6 votes vote down vote up
def _handle_ast_list(self, ast_list):
        """
        Find unreachable nodes in the given sequence of ast nodes.
        """
        for index, node in enumerate(ast_list):
            if isinstance(
                node, (ast.Break, ast.Continue, ast.Raise, ast.Return)
            ):
                try:
                    first_unreachable_node = ast_list[index + 1]
                except IndexError:
                    continue
                class_name = node.__class__.__name__.lower()
                self._define(
                    self.unreachable_code,
                    class_name,
                    first_unreachable_node,
                    last_node=ast_list[-1],
                    message="unreachable code after '{class_name}'".format(
                        **locals()
                    ),
                    confidence=100,
                )
                return 
Example #6
Source File: function.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def _check_sub_node(
        self,
        node: AnyFunctionDef,
        sub_node: ast.AST,
    ) -> None:
        if isinstance(sub_node, ast.Name):
            if isinstance(sub_node.ctx, ast.Store):
                self._update_variables(node, sub_node)

        error_counters: _NodeTypeHandler = {
            ast.Return: self.returns,
            ast.Expr: self.expressions,
            ast.Await: self.awaits,
            ast.Assert: self.asserts,
        }

        for types, counter in error_counters.items():
            if isinstance(sub_node, types):
                counter[node] += 1 
Example #7
Source File: keywords.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def _check_last_return_in_function(self, node: ast.Return) -> None:
        parent = get_parent(node)
        if not isinstance(parent, FunctionNodes):
            return

        returns = len(tuple(filter(
            lambda return_node: return_node.value is not None,
            walk.get_subnodes_by_type(parent, ast.Return),
        )))

        last_value_return = (
            len(parent.body) > 1 and
            returns < 2 and
            isinstance(node.value, ast.NameConstant) and
            node.value.value is None
        )

        one_return_with_none = (
            returns == 1 and
            isinstance(node.value, ast.NameConstant) and
            node.value.value is None
        )

        if node.value is None or last_value_return or one_return_with_none:
            self.add_violation(InconsistentReturnViolation(node)) 
Example #8
Source File: ComponentLevel3.py    From pymtl3 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _floodfill_nets( signal_list, adjacency ):
    """ Floodfill to find out connected nets. Return a list of sets. """

    nets = []
    visited = set()
    pred    = {} # detect cycle that has >=3 nodes
    for obj in signal_list:
      # If obj has adjacent signals
      if obj in adjacency and obj not in visited:
        net = set()
        Q   = [ obj ]
        while Q:
          u = Q.pop()
          visited.add( u )
          net.add( u )
          for v in adjacency[u]:
            if v not in visited:
              pred[v] = u
              Q.append( v )
            elif v is not pred[u]:
              raise InvalidConnectionError(repr(v)+" is in a connection loop.")
        if len(net) == 1:
          continue
        nets.append( net )
    return nets 
Example #9
Source File: keywords.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def _get_previous_stmt(self, node: ast.Return) -> Optional[ast.stmt]:
        """
        This method gets the previous node in a block.

        It is kind of strange. Because nodes might have several bodies.
        Like ``try`` or ``for`` or ``if`` nodes.
        ``return`` can also be the only statement there.

        We also use ``cast`` for a reason.
        Because ``return`` always has a parent.
        """
        parent = cast(ast.AST, get_parent(node))
        for part in ('body', 'orelse', 'finalbody'):
            block = getattr(parent, part, [])
            try:
                current_index = block.index(node)
            except ValueError:
                continue

            if current_index > 0:
                return block[current_index - 1]
        return None 
Example #10
Source File: topython.py    From pyrser with GNU General Public License v3.0 6 votes vote down vote up
def __exit_scope(self) -> ast.stmt:
        """Create the appropriate scope exiting statement.

        The documentation only shows one level and always uses
        'return False' in examples.

        'raise AltFalse()' within a try.
        'break' within a loop.
        'return False' otherwise.
        """
        if self.in_optional:
            return ast.Pass()
        if self.in_try:
            return ast.Raise(
                ast.Call(ast.Name('AltFalse', ast.Load()), [], [], None, None),
                None)
        if self.in_loop:
            return ast.Break()
        return ast.Return(ast.Name('False', ast.Load()))

    #TODO(bps): find a better name to describe what this does 
Example #11
Source File: bugbear.py    From flake8-bugbear with MIT License 6 votes vote down vote up
def check_for_b012(self, node):
        def _loop(node, bad_node_types):
            if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):
                return

            if isinstance(node, (ast.While, ast.For)):
                bad_node_types = (ast.Return,)

            elif isinstance(node, bad_node_types):
                self.errors.append(B012(node.lineno, node.col_offset))

            for child in ast.iter_child_nodes(node):
                _loop(child, bad_node_types)

        for child in node.finalbody:
            _loop(child, (ast.Return, ast.Continue, ast.Break)) 
Example #12
Source File: _ast_to_ir2.py    From tmppy with Apache License 2.0 6 votes vote down vote up
def return_stmt_ast_to_ir2(ast_node: ast.Return,
                           compilation_context: CompilationContext):
    expression = ast_node.value
    if not expression:
        raise CompilationError(compilation_context, ast_node,
                               'Return statements with no returned expression are not supported.')

    expression = expression_ast_to_ir2(expression,
                                       compilation_context,
                                       in_match_pattern=False,
                                       check_var_reference=lambda ast_node: None,
                                       match_lambda_argument_names=set(),
                                       current_stmt_line=ast_node.lineno)

    return ir2.ReturnStmt(expr=expression,
                          source_branch=SourceBranch(compilation_context.filename,
                                                     ast_node.lineno,
                                                     -compilation_context.current_function_definition_line)) 
Example #13
Source File: function_description.py    From darglint with MIT License 6 votes vote down vote up
def _has_return(fun):
    # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool
    """Return true if the function has a fruitful return.

    Args:
        fun: A function node to check.

    Returns:
        True if there is a fruitful return, otherwise False.

    """
    def skip(f):
        return f != fun and isinstance(f, FunctionDef)

    for node in _walk(fun, skip):
        if isinstance(node, ast.Return) and node.value is not None:
            return True
    return False 
Example #14
Source File: expressionfunction.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def visit(self, node) -> Any:
        if isinstance(node, ast.Name):
            if isinstance(node.ctx, ast.Load):
                self.loaded.add(node.id)
            elif isinstance(node.ctx, ast.Store):
                self.stored.add(node.id)
        elif isinstance(node, ast.Return):
            self.has_return = True
        # We must keep track of importer name in order to avoid considering as variable
        # names:
        elif isinstance(node, ast.Import):
            self.imported.update([ n.name for n in node.names])
        elif isinstance(node, ast.ImportFrom):
            self.imported.update([ n.name for n in node.names])

        self.generic_visit(node) 
Example #15
Source File: bugbear.py    From flake8-bugbear with MIT License 6 votes vote down vote up
def check_for_b901(self, node):
        if node.name == "__await__":
            return

        has_yield = False
        return_node = None

        for parent, x in self.walk_function_body(node):
            # Only consider yield when it is part of an Expr statement.
            if isinstance(parent, ast.Expr) and isinstance(
                x, (ast.Yield, ast.YieldFrom)
            ):
                has_yield = True

            if isinstance(x, ast.Return) and x.value is not None:
                return_node = x

            if has_yield and return_node is not None:
                self.errors.append(B901(return_node.lineno, return_node.col_offset))
                break 
Example #16
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_return_stmt_2(p):
    '''return_stmt : RETURN testlist'''
    #                     1        2
    p[0] = ast.Return(p[2], rule=inspect.currentframe().f_code.co_name, **p[1][1])

# yield_stmt: yield_expr 
Example #17
Source File: keywords.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_consistent_variable_return(self, node: ast.Return) -> None:
        if not node.value or not self._is_named_return(node):
            return

        previous_node = self._get_previous_stmt(node)
        if not isinstance(previous_node, AssignNodes):
            return

        return_names = name_nodes.get_variables_from_node(node.value)
        previous_names = list(name_nodes.flat_variable_names([previous_node]))
        self._check_for_violations(node, return_names, previous_names) 
Example #18
Source File: keywords.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _is_named_return(self, node: ast.Return) -> bool:
        if isinstance(node.value, ast.Name):
            return True
        return (
            isinstance(node.value, ast.Tuple) and
            all(isinstance(elem, ast.Name) for elem in node.value.elts)
        ) 
Example #19
Source File: code_to_r1cs.py    From research with MIT License 5 votes vote down vote up
def flatten_stmt(stmt):
    # Get target variable
    if isinstance(stmt, ast.Assign):
        assert len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name)
        target = stmt.targets[0].id
    elif isinstance(stmt, ast.Return):
        target = '~out'
    # Get inner content
    return flatten_expr(target, stmt.value)

# Main method for flattening an expression 
Example #20
Source File: code_to_r1cs.py    From research with MIT License 5 votes vote down vote up
def extract_inputs_and_body(code):
    o = []
    if len(code) != 1 or not isinstance(code[0], ast.FunctionDef):
        raise Exception("Expecting function declaration")
    # Gather the list of input variables
    inputs = []
    for arg in code[0].args.args:
        if isinstance(arg, ast.arg):
            assert isinstance(arg.arg, str)
            inputs.append(arg.arg)
        elif isinstance(arg, ast.Name):
            inputs.append(arg.id)
        else:
            raise Exception("Invalid arg: %r" % ast.dump(arg))
    # Gather the body
    body = []
    returned = False
    for c in code[0].body:
        if not isinstance(c, (ast.Assign, ast.Return)):
            raise Exception("Expected variable assignment or return")
        if returned:
            raise Exception("Cannot do stuff after a return statement")
        if isinstance(c, ast.Return):
            returned = True
        body.append(c)
    return inputs, body

# Convert a body with potentially complex expressions into
# simple expressions of the form x = y or x = y * z 
Example #21
Source File: keywords.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_for_violations(
        self,
        node: ast.Return,
        return_names: List[str],
        previous_names: List[str],
    ) -> None:
        if previous_names == return_names:
            self.add_violation(
                InconsistentReturnVariableViolation(
                    node, text=', '.join(return_names),
                ),
            ) 
Example #22
Source File: core.py    From vulture with MIT License 5 votes vote down vote up
def get_unused_code(self, min_confidence=0, sort_by_size=False):
        """
        Return ordered list of unused Item objects.
        """
        if not 0 <= min_confidence <= 100:
            raise ValueError("min_confidence must be between 0 and 100.")

        def by_name(item):
            return (item.filename.lower(), item.first_lineno)

        def by_size(item):
            return (item.size,) + by_name(item)

        unused_code = (
            self.unused_attrs
            + self.unused_classes
            + self.unused_funcs
            + self.unused_imports
            + self.unused_methods
            + self.unused_props
            + self.unused_vars
            + self.unreachable_code
        )

        confidently_unused = [
            obj for obj in unused_code if obj.confidence >= min_confidence
        ]

        return sorted(
            confidently_unused, key=by_size if sort_by_size else by_name
        ) 
Example #23
Source File: definitions.py    From vkbottle with MIT License 5 votes vote down vote up
def return_statement(d: ast.Return):
    value = "null" if d is None else find(d.value)
    return f"return {value};" 
Example #24
Source File: python2ir.py    From ppci with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def gen_statement(self, statement):
        """ Generate code for a statement """
        if isinstance(statement, list):
            for inner_statement in statement:
                self.gen_statement(inner_statement)
        else:
            with self.use_location(statement):
                if isinstance(statement, ast.Pass):
                    pass  # No comments :)
                elif isinstance(statement, ast.Return):
                    self.gen_return(statement)
                elif isinstance(statement, ast.If):
                    self.gen_if(statement)
                elif isinstance(statement, ast.While):
                    self.gen_while(statement)
                elif isinstance(statement, ast.Break):
                    self.gen_break(statement)
                elif isinstance(statement, ast.Continue):
                    self.gen_continue(statement)
                elif isinstance(statement, ast.For):
                    self.gen_for(statement)
                elif isinstance(statement, ast.Assign):
                    self.gen_assign(statement)
                elif isinstance(statement, ast.Expr):
                    self.gen_expr(statement.value)
                elif isinstance(statement, ast.AugAssign):
                    self.gen_aug_assign(statement)
                else:  # pragma: no cover
                    self.not_impl(statement) 
Example #25
Source File: test_Parser.py    From hope with GNU General Public License v3.0 5 votes vote down vote up
def test_get_fkt_ast_simple(self):
        fkt_ast = get_fkt_ast(dummy)
        assert fkt_ast is not None
        assert isinstance(fkt_ast, ast.FunctionDef)
        assert len(fkt_ast.body)==1
        assert isinstance(fkt_ast.body[0], ast.Return)
        
    #TODO: how can I cause an exception? Add a new test 
Example #26
Source File: cps.py    From kappa with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visit_Return(self, ret: ast.Return, _ctx: CPSTransformerContext) -> VisitReturnT:
        return ret, [] 
Example #27
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_return_stmt_1(p):
    '''return_stmt : RETURN'''
    #                     1
    p[0] = ast.Return(None, rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #28
Source File: astutil.py    From deco with MIT License 5 votes vote down vote up
def generic_visit(self, node):
        if (isinstance(node, ast.stmt) and self.references_arg(node)) or isinstance(node, ast.Return):
            return self.get_waits() + [node]
        return NodeTransformer.generic_visit(self, node) 
Example #29
Source File: _343.py    From codetransformer with GNU General Public License v2.0 5 votes vote down vote up
def _return(instr, queue, stack, body, context):
    if context.in_function_block:
        body.append(ast.Return(value=make_expr(stack)))
    elif context.in_lambda:
        if body:
            raise DecompilationError("Non-empty body in lambda: %s" % body)
        # Just append the raw expr.  We'll extract the raw value in
        # `make_lambda`.
        body.append(make_expr(stack))
    else:
        _check_stack_for_module_return(stack)
        # Pop dummy LOAD_CONST(None) at the end of a module.
        stack.pop()
        return 
Example #30
Source File: utils.py    From BibleBot with GNU General Public License v3.0 5 votes vote down vote up
def insert_returns(body):  # for +eval, thanks to nitros12 on github for the code
    # insert return stmt if the last expression is a expression statement
    if isinstance(body[-1], ast.Expr):
        body[-1] = ast.Return(body[-1].value)
        ast.fix_missing_locations(body[-1])

    # for if statements, we insert returns into the body and the orelse
    if isinstance(body[-1], ast.If):
        insert_returns(body[-1].body)
        insert_returns(body[-1].orelse)

    # for with blocks, again we insert returns into the body
    if isinstance(body[-1], ast.With):
        insert_returns(body[-1].body)