Python ast.TryFinally() Examples

The following are 16 code examples of ast.TryFinally(). 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: checker.py    From linter-pylama with MIT License 6 votes vote down vote up
def CONTINUE(self, node):
        # Walk the tree up until we see a loop (OK), a function or class
        # definition (not OK), for 'continue', a finally block (not OK), or
        # the top module scope (not OK)
        n = node
        while hasattr(n, 'parent'):
            n, n_child = n.parent, n
            if isinstance(n, LOOP_TYPES):
                # Doesn't apply unless it's in the loop itself
                if n_child not in n.orelse:
                    return
            if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
                break
            # Handle Try/TryFinally difference in Python < and >= 3.3
            if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
                if n_child in n.finalbody:
                    self.report(messages.ContinueInFinally, node)
                    return
        if isinstance(node, ast.Continue):
            self.report(messages.ContinueOutsideLoop, node)
        else:  # ast.Break
            self.report(messages.BreakOutsideLoop, node) 
Example #2
Source File: checker.py    From pyflakes with MIT License 6 votes vote down vote up
def CONTINUE(self, node):
        # Walk the tree up until we see a loop (OK), a function or class
        # definition (not OK), for 'continue', a finally block (not OK), or
        # the top module scope (not OK)
        n = node
        while hasattr(n, '_pyflakes_parent'):
            n, n_child = n._pyflakes_parent, n
            if isinstance(n, LOOP_TYPES):
                # Doesn't apply unless it's in the loop itself
                if n_child not in n.orelse:
                    return
            if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
                break
            # Handle Try/TryFinally difference in Python < and >= 3.3
            if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
                if n_child in n.finalbody and not PY38_PLUS:
                    self.report(messages.ContinueInFinally, node)
                    return
        if isinstance(node, ast.Continue):
            self.report(messages.ContinueOutsideLoop, node)
        else:  # ast.Break
            self.report(messages.BreakOutsideLoop, node) 
Example #3
Source File: checker.py    From blackmamba with MIT License 6 votes vote down vote up
def CONTINUE(self, node):
        # Walk the tree up until we see a loop (OK), a function or class
        # definition (not OK), for 'continue', a finally block (not OK), or
        # the top module scope (not OK)
        n = node
        while hasattr(n, 'parent'):
            n, n_child = n.parent, n
            if isinstance(n, LOOP_TYPES):
                # Doesn't apply unless it's in the loop itself
                if n_child not in n.orelse:
                    return
            if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
                break
            # Handle Try/TryFinally difference in Python < and >= 3.3
            if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
                if n_child in n.finalbody:
                    self.report(messages.ContinueInFinally, node)
                    return
        if isinstance(node, ast.Continue):
            self.report(messages.ContinueOutsideLoop, node)
        else:  # ast.Break
            self.report(messages.BreakOutsideLoop, node) 
Example #4
Source File: ast2.py    From gast with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def visit_Try(self, node):
        if node.finalbody:
            new_node = ast.TryFinally(
                self._visit(node.body),
                self._visit(node.finalbody)
            )
        else:
            new_node = ast.TryExcept(
                self._visit(node.body),
                self._visit(node.handlers),
                self._visit(node.orelse),
            )
        ast.copy_location(new_node, node)
        return new_node

    # expr 
Example #5
Source File: checker.py    From linter-pylama with MIT License 5 votes vote down vote up
def getAlternatives(n):
        if isinstance(n, (ast.If, ast.TryFinally)):
            return [n.body]
        if isinstance(n, ast.TryExcept):
            return [n.body + n.orelse] + [[hdl] for hdl in n.handlers] 
Example #6
Source File: ast_generator.py    From bigcode-tools with MIT License 5 votes vote down vote up
def is_try(node):
        return hasattr(ast, "Try") and isinstance(node, ast.Try) or \
               hasattr(ast, "TryExcept") and isinstance(node, ast.TryExcept) or \
               hasattr(ast, "TryFinally") and isinstance(node, ast.TryFinally) 
Example #7
Source File: checker.py    From pyflakes with MIT License 5 votes vote down vote up
def getAlternatives(n):
        if isinstance(n, (ast.If, ast.TryFinally)):
            return [n.body]
        if isinstance(n, ast.TryExcept):
            return [n.body + n.orelse] + [[hdl] for hdl in n.handlers] 
Example #8
Source File: checker.py    From blackmamba with MIT License 5 votes vote down vote up
def getNodeType(node_class):
        return node_class.__name__.upper()

# Python >= 3.3 uses ast.Try instead of (ast.TryExcept + ast.TryFinally) 
Example #9
Source File: checker.py    From blackmamba with MIT License 5 votes vote down vote up
def getAlternatives(n):
        if isinstance(n, (ast.If, ast.TryFinally)):
            return [n.body]
        if isinstance(n, ast.TryExcept):
            return [n.body + n.orelse] + [[hdl] for hdl in n.handlers] 
Example #10
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_try_stmt_2(p):
    '''try_stmt : TRY COLON suite try_stmt_plus FINALLY COLON suite'''
    #               1     2     3             4       5     6     7
    p[0] = ast.TryFinally([ast.TryExcept(p[3], p[4], [], rule=inspect.currentframe().f_code.co_name, **p[1][1])], p[7], rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #11
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_try_stmt_4(p):
    '''try_stmt : TRY COLON suite try_stmt_plus ELSE COLON suite FINALLY COLON suite'''
    #               1     2     3             4    5     6     7       8     9    10
    p[0] = ast.TryFinally([ast.TryExcept(p[3], p[4], p[7], rule=inspect.currentframe().f_code.co_name, **p[1][1])], p[10], rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #12
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_try_stmt_5(p):
    '''try_stmt : TRY COLON suite FINALLY COLON suite'''
    #               1     2     3       4     5     6
    p[0] = ast.TryFinally(p[3], p[6], rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #13
Source File: checker.py    From Transcrypt with Apache License 2.0 5 votes vote down vote up
def getNodeType(node_class):
        return node_class.__name__.upper()

# Python >= 3.3 uses ast.Try instead of (ast.TryExcept + ast.TryFinally) 
Example #14
Source File: checker.py    From Transcrypt with Apache License 2.0 5 votes vote down vote up
def getAlternatives(n):
        if isinstance(n, (ast.If, ast.TryFinally)):
            return [n.body]
        if isinstance(n, ast.TryExcept):
            return [n.body + n.orelse] + [[hdl] for hdl in n.handlers] 
Example #15
Source File: translation.py    From mochi with MIT License 4 votes vote down vote up
def translate_try(self, exp):
        if len(exp) < 2:
            raise MochiSyntaxError(exp, self.filename)
        body_exp = []
        handler_exps = []
        orelse_exp = []
        final_body_exp = []
        for expr in exp:
            if issequence_except_str(expr) and len(expr) > 1 and isinstance(expr[0], Symbol):
                expr_name = expr[0].name
                if expr_name == 'finally':
                    final_body_exp = expr[1:]
                    continue
                elif expr_name == 'orelse':
                    orelse_exp = expr[1:]
                    continue
                elif expr_name == 'except':
                    handler_exps.append(expr[1:])
                    continue
            body_exp.append(expr)

        body = self._translate_sequence(body_exp, True)
        handlers = self._translate_handlers(handler_exps)
        orelse = self._translate_sequence(orelse_exp, True)
        final_body = self._translate_sequence(final_body_exp, True)
        if GE_PYTHON_34:
            return (ast.Try(body=body,
                            handlers=handlers,
                            orelse=orelse,
                            finalbody=final_body,
                            lineno=exp[0].lineno,
                            col_offset=0),), self.translate(EMPTY_SYM, False)[1]
        else:
            if len(handlers) == 0:
                return (ast.TryFinally(body=body,
                                       finalbody=final_body,
                                       lineno=exp[0].lineno,
                                       col_offset=0),), self.translate(EMPTY_SYM, False)[1]
            else:
                return (ast.TryFinally(body=[ast.TryExcept(body=body,
                                                           handlers=handlers,
                                                           orelse=orelse,
                                                           lineno=exp[0].lineno,
                                                           col_offset=0)],
                                       finalbody=final_body,
                                       lineno=exp[0].lineno,
                                       col_offset=0),), self.translate(EMPTY_SYM, False)[1] 
Example #16
Source File: ast_utils.py    From pasta with Apache License 2.0 4 votes vote down vote up
def get_last_child(node):
  """Get the last child node of a block statement.

  The input must be a block statement (e.g. ast.For, ast.With, etc).

  Examples:
    1. with first():
         second()
         last()

    2. try:
         first()
       except:
         second()
       finally:
         last()

  In both cases, the last child is the node for `last`.
  """
  if isinstance(node, ast.Module):
    try:
      return node.body[-1]
    except IndexError:
      return None
  if isinstance(node, ast.If):
    if (len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If) and
        fmt.get(node.orelse[0], 'is_elif')):
      return get_last_child(node.orelse[0])
    if node.orelse:
      return node.orelse[-1]
  elif isinstance(node, ast.With):
    if (len(node.body) == 1 and isinstance(node.body[0], ast.With) and
        fmt.get(node.body[0], 'is_continued')):
      return get_last_child(node.body[0])
  elif hasattr(ast, 'Try') and isinstance(node, ast.Try):
    if node.finalbody:
      return node.finalbody[-1]
    if node.orelse:
      return node.orelse[-1]
  elif hasattr(ast, 'TryFinally') and isinstance(node, ast.TryFinally):
    if node.finalbody:
      return node.finalbody[-1]
  elif hasattr(ast, 'TryExcept') and isinstance(node, ast.TryExcept):
    if node.orelse:
      return node.orelse[-1]
    if node.handlers:
      return get_last_child(node.handlers[-1])
  return node.body[-1]