Python ast.withitem() Examples

The following are 12 code examples of ast.withitem(). 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: prints.py    From deal with MIT License 6 votes vote down vote up
def handle_with(expr) -> Optional[Token]:
    token_info = dict(line=expr.lineno, col=expr.col_offset)
    for item in expr.items:
        if isinstance(item, ast.withitem):
            item = item.context_expr
        else:
            item = item[0]
        if _is_pathlib_write(item):
            return Token(value='Path.open', **token_info)
        if not isinstance(item, TOKENS.CALL):
            continue
        name = get_name(item.func)
        if name == 'open':
            if _is_open_to_write(item):
                return Token(value='open', **token_info)
    return None 
Example #2
Source File: _343.py    From codetransformer with GNU General Public License v2.0 6 votes vote down vote up
def make_withitem(queue, stack):
    """
    Make an ast.withitem node.
    """
    context_expr = make_expr(stack)
    # This is a POP_TOP for just "with <expr>:".
    # This is a STORE_NAME(name) for "with <expr> as <name>:".
    as_instr = queue.popleft()
    if isinstance(as_instr, (instrs.STORE_FAST,
                             instrs.STORE_NAME,
                             instrs.STORE_DEREF,
                             instrs.STORE_GLOBAL)):
        return ast.withitem(
            context_expr=context_expr,
            optional_vars=make_assign_target(as_instr, queue, stack),
        )
    elif isinstance(as_instr, instrs.POP_TOP):
        return ast.withitem(context_expr=context_expr, optional_vars=None)
    else:
        raise DecompilationError(
            "Don't know how to make withitem from %s" % as_instr,
        ) 
Example #3
Source File: translation.py    From mochi with MIT License 6 votes vote down vote up
def translate_with_34(self, exp):
        keyword_with, items, *body = exp
        pre = []
        items_py = []
        for item in items:
            item_pre, item_value = self.translate(item[0], False)
            pre.extend(item_pre)
            var = item[1]
            items_py.append(ast.withitem(context_expr=item_value,
                                         optional_vars=ast.Name(id=var.name,
                                                                ctx=ast.Store(),
                                                                lineno=var.lineno,
                                                                col_offset=0),
                                         lineno=var.lineno,
                                         col_offset=0))

        body_py = self._translate_sequence(body, True)
        pre.append(ast.With(items=items_py,
                            body=body_py,
                            lineno=keyword_with.lineno,
                            col_offset=0))
        return pre, self.translate(NONE_SYM, False)[1] 
Example #4
Source File: blocks.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def visit_withitem(self, node: ast.withitem) -> None:
        """
        Visits ``with`` and ``async with`` declarations.

        Raises:
            BlockAndLocalOverlapViolation

        """
        if node.optional_vars:
            parent = cast(AnyWith, get_parent(node))
            names = defs.extract_names(node.optional_vars)
            self._scope(parent, names, is_local=False)
            self._outer_scope(parent, names)
        self.generic_visit(node)

    # Locals: 
Example #5
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_with(self):
        p = ast.Pass()
        self.stmt(ast.With([], [p]), "empty items on With")
        i = ast.withitem(ast.Num(3), None)
        self.stmt(ast.With([i], []), "empty body on With")
        i = ast.withitem(ast.Name("x", ast.Store()), None)
        self.stmt(ast.With([i], [p]), "must have Load context")
        i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
        self.stmt(ast.With([i], [p]), "must have Store context") 
Example #6
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_with(self):
        p = ast.Pass()
        self.stmt(ast.With([], [p]), "empty items on With")
        i = ast.withitem(ast.Num(3), None)
        self.stmt(ast.With([i], []), "empty body on With")
        i = ast.withitem(ast.Name("x", ast.Store()), None)
        self.stmt(ast.With([i], [p]), "must have Load context")
        i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
        self.stmt(ast.With([i], [p]), "must have Store context") 
Example #7
Source File: tracer.py    From executing with MIT License 5 votes vote down vote up
def visit_stmt(self, node):
        # type: (ast.stmt) -> ast.With
        """
        Every statement in the original code becomes:

        with _treetrace_hidden_with_stmt(_tree_index):
            <statement>

        where the _treetrace_hidden_with_stmt function is the the corresponding method with the
        TreeTracerBase and traced_file arguments already filled in (see _trace_methods_dict)
        """
        context_expr = self._create_simple_marker_call(
            super(_NodeVisitor, self).generic_visit(node),
            TreeTracerBase._treetrace_hidden_with_stmt)

        if PY3:
            wrapped = ast.With(
                items=[ast.withitem(context_expr=context_expr)],
                body=[node],
            )
        else:
            wrapped = ast.With(
                context_expr=context_expr,
                body=[node],
            )
        ast.copy_location(wrapped, node)
        ast.fix_missing_locations(wrapped)
        return wrapped 
Example #8
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_with(self):
        p = ast.Pass()
        self.stmt(ast.With([], [p]), "empty items on With")
        i = ast.withitem(ast.Num(3), None)
        self.stmt(ast.With([i], []), "empty body on With")
        i = ast.withitem(ast.Name("x", ast.Store()), None)
        self.stmt(ast.With([i], [p]), "must have Load context")
        i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
        self.stmt(ast.With([i], [p]), "must have Store context") 
Example #9
Source File: functions.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_open_call_context(self, node: ast.Call) -> None:
        function_name = functions.given_function_called(node, {'open'})
        if not function_name:
            return

        if isinstance(nodes.get_parent(node), ast.withitem):
            # We do not care about `with` or `async with` - both are fine.
            return

        self.add_violation(OpenWithoutContextManagerViolation(node)) 
Example #10
Source File: naming.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def visit_withitem(self, node: ast.withitem) -> None:
        """
        Checks that we cannot create explicit unused context variables.

        Raises:
            UnusedVariableIsDefinedViolation

        """
        if node.optional_vars:
            self._check_assign_unused(
                cast(ast.AST, nodes.get_parent(node)),
                name_nodes.get_variables_from_node(node.optional_vars),
                is_local=True,
            )
        self.generic_visit(node) 
Example #11
Source File: blocks.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def visit_withitem(self, node: ast.withitem) -> None:
        """Visits ``with`` and ``async with`` declarations."""
        if node.optional_vars:
            self._add_to_scope(
                cast(AnyWith, get_parent(node)),
                defs.extract_names(node.optional_vars),
            )
        self.generic_visit(node)

    # Variable usages: 
Example #12
Source File: keywords.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def visit_withitem(self, node: ast.withitem) -> None:
        """
        Checks that all variables inside context managers defined correctly.

        Raises:
            ContextManagerVariableDefinitionViolation

        """
        self._check_variable_definitions(node)
        self.generic_visit(node)