Python ast.Load() Examples

The following are code examples for showing how to use ast.Load(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_ast.py    GNU Lesser General Public License v3.0 7 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 2
Project: python-minifier   Author: dflook   File: resolve_names.py    MIT License 6 votes vote down vote up
def resolve_names(node):
    """
    Resolve unbound names to a NameBinding

    :param node: The module to resolve names in
    :type node: :class:`ast.Module`

    """

    if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
        get_binding(node.id, node.namespace).add_reference(node)
    elif hasattr(ast, 'Exec') and isinstance(node, ast.Exec):
        get_global_namespace(node).tainted = True

    for child in ast.iter_child_nodes(node):
        resolve_names(child) 
Example 3
Project: Lyra   Author: caterinaurban   File: cfg_generator.py    Mozilla Public License 2.0 6 votes vote down vote up
def visit_Name(self, node, types=None, typ=None):
        """Visitor function for a variable name.
        The attribute id stores the name as a string.
        The attribute ctx is Store (to assign a new value to the variable),
        Load (to load the value of the variable), or Del (to delete the variable)."""
        pp = ProgramPoint(node.lineno, node.col_offset)
        if isinstance(node.ctx, ast.Store):
            if node.id not in types:
                if typ:
                    types[node.id] = typ
                else:
                    raise ValueError(f"Missing type annotation for variable {node.id}!")
            expr = VariableIdentifier(types[node.id], node.id)
            return VariableAccess(pp, types[node.id], expr)
        if isinstance(node.ctx, ast.Load):
            assert node.id in types
            # assert types[node.id] == typ or typ is None
            expr = VariableIdentifier(types[node.id], node.id)
            return VariableAccess(pp, types[node.id], expr)
        assert isinstance(node.ctx, ast.Del)
        raise NotImplementedError(f"Name deletion is unsupported!")

    # Expressions

    # noinspection PyUnusedLocal 
Example 4
Project: Lyra   Author: caterinaurban   File: cfg_generator.py    Mozilla Public License 2.0 6 votes vote down vote up
def visit_Subscript(self, node, types=None, typ=None):
        """Visitor function for a subscript.
        The attribute value stores the target of the subscript (often a Name).
        The attribute slice is one of Index, Slice, or ExtSlice.
        The attribute ctx is Load, Store, or Del."""
        pp = ProgramPoint(node.lineno, node.col_offset)
        if isinstance(node.slice, ast.Index):
            target = self.visit(node.value, types, None)
            key = self.visit(node.slice.value, types, None)
            return SubscriptionAccess(pp, typ, target, key)
        elif isinstance(node.slice, ast.Slice):
            value = self.visit(node.value, types, None)
            lower = self.visit(node.slice.lower, types, None)
            upper = self.visit(node.slice.upper, types, None) if node.slice.upper else None
            step = self.visit(node.slice.step, types, None) if node.slice.step else None
            return SlicingAccess(pp, typ, value, lower, upper, step)
        raise NotImplementedError(f"Subscription {node.slice.__class__.__name__} is unsupported!")

    # Statements 
Example 5
Project: miniast   Author: cpcloud   File: base.py    Apache License 2.0 6 votes vote down vote up
def to_node(value):
    if isinstance(value, str):
        return ast.Str(s=value)
    elif isinstance(value, (int, float)):
        return ast.Num(n=value)
    elif isinstance(value, list):
        return ast.List(elts=list(map(to_node, value)), ctx=ast.Load())
    elif isinstance(value, tuple):
        return ast.Tuple(elts=list(map(to_node, value)), ctx=ast.Load())
    elif isinstance(value, dict):
        keys = list(map(to_node, value.keys()))
        values = list(map(to_node, value.values()))
        return ast.Dict(keys=keys, values=values)
    elif isinstance(value, set):
        return ast.Set(elts=list(map(to_node, value)))
    assert value is None or isinstance(value, ast.AST), \
        'value must be None or AST instance, got {}'.format(
            type(value).__name__
        )
    return value 
Example 6
Project: miniast   Author: cpcloud   File: test_miniast.py    Apache License 2.0 6 votes vote down vote up
def eq(a, b):
    """Test equality of AST nodes, because Python doesn't define __eq__ for
    them :(
    """
    if isinstance(a, (ast.Load, ast.Store)):
        return isinstance(b, type(a))
    if isinstance(a, list):
        return isinstance(b, list) and all(map(eq, a, b))
    return a == b or (
        isinstance(a, type(b)) and
        isinstance(b, type(a)) and
        hasattr(a, '_fields') and
        hasattr(b, '_fields') and
        a._fields == b._fields and
        all(eq(getattr(a, field), getattr(b, field)) for field in a._fields)
    ) 
Example 7
Project: miniast   Author: cpcloud   File: test_miniast.py    Apache License 2.0 6 votes vote down vote up
def test_call():
    assert eq(
        var.foo(1, 2),
        ast.Call(
            func=ast.Name(id='foo', ctx=ast.Load()),
            args=[n(1), n(2)],
            keywords=[],
        )
    )
    assert eq(
        var.func(var.a, b=var.b),
        ast.Call(
            func=ast.Name(id='func', ctx=ast.Load()),
            args=[ast.Name(id='a', ctx=ast.Load())],
            keywords=[
                ast.keyword(arg='b', value=ast.Name(id='b', ctx=ast.Load()))
            ]
        )
    ) 
Example 8
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.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=[]))])"
        )
        self.assertEqual(ast.dump(node, annotate_fields=False),
            "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
            "Str('and cheese')], []))])"
        )
        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=[], "
            "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
        ) 
Example 9
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 6 votes vote down vote up
def test_classdef(self):
        def cls(bases=None, keywords=None, body=None, decorator_list=None):
            if bases is None:
                bases = []
            if keywords is None:
                keywords = []
            if body is None:
                body = [ast.Pass()]
            if decorator_list is None:
                decorator_list = []
            return ast.ClassDef("myclass", bases, keywords,
                                body, decorator_list)
        self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
                  "must have Load context")
        self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
                  "must have Load context")
        self.stmt(cls(body=[]), "empty body on ClassDef")
        self.stmt(cls(body=[None]), "None disallowed")
        self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
                  "must have Load context") 
Example 10
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 6 votes vote down vote up
def test_try(self):
        p = ast.Pass()
        t = ast.Try([], [], [], [p])
        self.stmt(t, "empty body on Try")
        t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
        self.stmt(t, "must have Load context")
        t = ast.Try([p], [], [], [])
        self.stmt(t, "Try has neither except handlers nor finalbody")
        t = ast.Try([p], [], [p], [p])
        self.stmt(t, "Try has orelse but no except handlers")
        t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
        self.stmt(t, "empty body on ExceptHandler")
        e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
        self.stmt(ast.Try([p], e, [], []), "must have Load context")
        e = [ast.ExceptHandler(None, "x", [p])]
        t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
        self.stmt(t, "must have Load context")
        t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
        self.stmt(t, "must have Load context") 
Example 11
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 6 votes vote down vote up
def test_subscript(self):
        sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
                            ast.Load())
        self.expr(sub, "must have Load context")
        x = ast.Name("x", ast.Load())
        sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
                            ast.Load())
        self.expr(sub, "must have Load context")
        s = ast.Name("x", ast.Store())
        for args in (s, None, None), (None, s, None), (None, None, s):
            sl = ast.Slice(*args)
            self.expr(ast.Subscript(x, sl, ast.Load()),
                      "must have Load context")
        sl = ast.ExtSlice([])
        self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
        sl = ast.ExtSlice([ast.Index(s)])
        self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context") 
Example 12
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: pytables.py    MIT License 6 votes vote down vote up
def visit_Attribute(self, node, **kwargs):
        attr = node.attr
        value = node.value

        ctx = node.ctx.__class__
        if ctx == ast.Load:
            # resolve the value
            resolved = self.visit(value)

            # try to get the value to see if we are another expression
            try:
                resolved = resolved.value
            except (AttributeError):
                pass

            try:
                return self.term_type(getattr(resolved, attr), self.env)
            except AttributeError:

                # something like datetime.datetime where scope is overridden
                if isinstance(value, ast.Name) and value.id == attr:
                    return resolved

        raise ValueError("Invalid Attribute context {name}".format(name=ctx.__name__)) 
Example 13
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: expr.py    MIT License 6 votes vote down vote up
def visit_Attribute(self, node, **kwargs):
        attr = node.attr
        value = node.value

        ctx = node.ctx
        if isinstance(ctx, ast.Load):
            # resolve the value
            resolved = self.visit(value).value
            try:
                v = getattr(resolved, attr)
                name = self.env.add_tmp(v)
                return self.term_type(name, self.env)
            except AttributeError:
                # something like datetime.datetime where scope is overridden
                if isinstance(value, ast.Name) and value.id == attr:
                    return resolved

        raise ValueError("Invalid Attribute context {name}".format(name=ctx.__name__)) 
Example 14
Project: YAPyPy   Author: Xython   File: extended_ast.py    MIT License 6 votes vote down vote up
def __init__(
            self,
            keys: t.List[ast.expr],
            values: t.List[ast.expr],
            ctx: t.Union[ast.Store, ast.Load],
            lineno=None,
            col_offset=None,
    ):
        super().__init__()
        self.keys = keys
        self.values = values
        self.ctx = ctx
        if lineno:
            self.lineno = lineno
        if col_offset:
            self.col_offset = col_offset 
Example 15
Project: recruit   Author: Frank-qlu   File: pytables.py    Apache License 2.0 6 votes vote down vote up
def visit_Attribute(self, node, **kwargs):
        attr = node.attr
        value = node.value

        ctx = node.ctx.__class__
        if ctx == ast.Load:
            # resolve the value
            resolved = self.visit(value)

            # try to get the value to see if we are another expression
            try:
                resolved = resolved.value
            except (AttributeError):
                pass

            try:
                return self.term_type(getattr(resolved, attr), self.env)
            except AttributeError:

                # something like datetime.datetime where scope is overridden
                if isinstance(value, ast.Name) and value.id == attr:
                    return resolved

        raise ValueError("Invalid Attribute context {name}"
                         .format(name=ctx.__name__)) 
Example 16
Project: recruit   Author: Frank-qlu   File: expr.py    Apache License 2.0 6 votes vote down vote up
def visit_Attribute(self, node, **kwargs):
        attr = node.attr
        value = node.value

        ctx = node.ctx
        if isinstance(ctx, ast.Load):
            # resolve the value
            resolved = self.visit(value).value
            try:
                v = getattr(resolved, attr)
                name = self.env.add_tmp(v)
                return self.term_type(name, self.env)
            except AttributeError:
                # something like datetime.datetime where scope is overridden
                if isinstance(value, ast.Name) and value.id == attr:
                    return resolved

        raise ValueError("Invalid Attribute context {name}"
                         .format(name=ctx.__name__)) 
Example 17
Project: Alexa-Ecovacs   Author: EtienneMD   File: rewrite.py    MIT License 6 votes vote down vote up
def pop_format_context(self, expl_expr):
        """Format the %-formatted string with current format context.

        The expl_expr should be an ast.Str instance constructed from
        the %-placeholders created by .explanation_param().  This will
        add the required code to format said string to .on_failure and
        return the ast.Name instance of the formatted string.

        """
        current = self.stack.pop()
        if self.stack:
            self.explanation_specifiers = self.stack[-1]
        keys = [ast.Str(key) for key in current.keys()]
        format_dict = ast.Dict(keys, list(current.values()))
        form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
        name = "@py_format" + str(next(self.variable_counter))
        self.on_failure.append(ast.Assign([ast.Name(name, ast.Store())], form))
        return ast.Name(name, ast.Load()) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_ast.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_invalid_identitifer(self):
        m = ast.Module([ast.Expr(ast.Name(u"x", ast.Load()))])
        ast.fix_missing_locations(m)
        with self.assertRaises(TypeError) as cm:
            compile(m, "<test>", "exec")
        self.assertIn("identifier must be of type str", str(cm.exception)) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_ast.py    GNU Lesser General Public License v3.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 20
Project: python-minifier   Author: dflook   File: binding.py    MIT License 5 votes vote down vote up
def rename(self, new_name):
        builtin = self._name
        super(BuiltinBinding, self).rename(new_name)
        self.namespace.body = list(
            insert(
                self.namespace.body,
                ast.Assign(
                    targets=[ast.Name(id=new_name, ctx=ast.Store())], value=ast.Name(id=builtin, ctx=ast.Load())
                ),
            )
        ) 
Example 21
Project: python-minifier   Author: dflook   File: rename_literals.py    MIT License 5 votes vote down vote up
def rename(self, new_name):

        for node in self.references:
            replace(node, ast.Name(id=new_name, ctx=ast.Load()))

        self._local_namespace.body = list(
            insert(self._local_namespace.body, ast.Assign(targets=[ast.Name(id=new_name, ctx=ast.Store())], value=self._value_node))
        )

        self._name = new_name 
Example 22
Project: python-minifier   Author: dflook   File: expressions.py    MIT License 5 votes vote down vote up
def List(draw, expression) -> ast.List:
    l = draw(lists(expression, min_size=0, max_size=3))
    return ast.List(elts=l, ctx=ast.Load()) 
Example 23
Project: python-minifier   Author: dflook   File: expressions.py    MIT License 5 votes vote down vote up
def Tuple(draw, expression) -> ast.Tuple:
    t = draw(lists(expression, min_size=0, max_size=3))
    return ast.Tuple(elts=t, ctx=ast.Load()) 
Example 24
Project: python-minifier   Author: dflook   File: expressions.py    MIT License 5 votes vote down vote up
def Attribute(draw, expression) -> ast.Attribute:
    value = draw(expression)
    attr = draw(text(alphabet=string.ascii_letters, min_size=1, max_size=3).filter(lambda n: n not in keyword.kwlist))
    return ast.Attribute(value, attr, ast.Load()) 
Example 25
Project: python-minifier   Author: dflook   File: expressions.py    MIT License 5 votes vote down vote up
def Subscript(draw, expression) -> ast.Subscript:
    value = draw(expression)
    attr = draw(text(alphabet=string.ascii_letters, min_size=1, max_size=3))
    return ast.Subscript(value, attr, ast.Load()) 
Example 26
Project: python-minifier   Author: dflook   File: expressions.py    MIT License 5 votes vote down vote up
def Subscript(draw, expression, ctx=ast.Load) -> ast.Subscript:
    return ast.Subscript(
        value=draw(expression),
        slice=draw(Index(expression) | Slice(expression) | ExtSlice(expression)),
        ctx=ctx()
    ) 
Example 27
Project: Lyra   Author: caterinaurban   File: cfg_generator.py    Mozilla Public License 2.0 5 votes vote down vote up
def visit_List(self, node, types=None, typ=None):
        """Visitor function for a list.
        The elts attribute stores a list of nodes representing the elements.
        The ctx attribute is Store if the container is an assignment target, and Load otherwise."""
        pp = ProgramPoint(node.lineno, node.col_offset)
        if isinstance(typ, ListLyraType):
            items = [self.visit(item, types, typ.typ) for item in node.elts]
        else:
            items = [self.visit(item, types, None) for item in node.elts]
        return ListDisplayAccess(pp, typ, items) 
Example 28
Project: Lyra   Author: caterinaurban   File: cfg_generator.py    Mozilla Public License 2.0 5 votes vote down vote up
def visit_Tuple(self, node, types=None, typ=None):
        """Visitor function for a tuple.
        The elts attribute stores a list of nodes representing the elements.
        The ctx attribute is Store if the container is an assignment target, and Load otherwise."""
        pp = ProgramPoint(node.lineno, node.col_offset)
        if isinstance(typ, TupleLyraType):
            items = [self.visit(item, types, i_typ) for item, i_typ in zip(node.elts, typ.typs)]
        else:
            items = [self.visit(item, types, None) for item in node.elts]
        return TupleDisplayAccess(pp, typ, items) 
Example 29
Project: smp_graphs   Author: x75   File: common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visit_Dict(self, node):
        print("node dict", node, dir(node))
        # return ast.copy_location(ast.Subscript(
        #     value=ast.Name(id='data', ctx=ast.Load()),
        #     slice=ast.Index(value=ast.Str(s=node.id)),
        #     ctx=node.ctx
        # ), node) 
Example 30
Project: smp_graphs   Author: x75   File: common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visit_Name(self, node):
        if node.id == 'lconf':
            print("node name", node.id, node.ctx) # dir(node)
            if isinstance(node.ctx, ast.Store):
                print("hu store", ast.parse(node.ctx))
        # return ast.copy_location(ast.Subscript(
        #     value=ast.Name(id='data', ctx=ast.Load()),
        #     slice=ast.Index(value=ast.Str(s=node.id)),
        #     ctx=node.ctx
        # ), node) 
Example 31
Project: Repobot   Author: Desgard   File: test_interactiveshell.py    MIT License 5 votes vote down vote up
def visit_Num(self, node):
        if isinstance(node.n, int):
            return ast.Call(func=ast.Name(id='Integer', ctx=ast.Load()),
                            args=[node], keywords=[])
        return node 
Example 32
Project: miniast   Author: cpcloud   File: base.py    Apache License 2.0 5 votes vote down vote up
def __getitem__(self, key):
        return Subscript(
            value=self,
            slice=ast.Index(value=to_node(key)),
            ctx=ast.Load()
        ) 
Example 33
Project: miniast   Author: cpcloud   File: base.py    Apache License 2.0 5 votes vote down vote up
def __getattr__(self, name):
        return Attribute(value=self, attr=name, ctx=ast.Load()) 
Example 34
Project: miniast   Author: cpcloud   File: base.py    Apache License 2.0 5 votes vote down vote up
def __getitem__(self, key):
        if isinstance(key, tuple):
            targets = [
                var[target] if isinstance(target, str) else to_node(target)
                for target in key
            ]
            return Tuple(elts=targets, ctx=ast.Load())
        return Name(id=key, ctx=ast.Load()) 
Example 35
Project: miniast   Author: cpcloud   File: test_miniast.py    Apache License 2.0 5 votes vote down vote up
def test_var():
    assert eq(var.foo, ast.Name(id='foo', ctx=ast.Load()))
    assert eq(var['bar'], ast.Name(id='bar', ctx=ast.Load())) 
Example 36
Project: miniast   Author: cpcloud   File: test_miniast.py    Apache License 2.0 5 votes vote down vote up
def test_attr():
    assert eq(
        var.foo.get_a_thing,
        Attribute(
            value=Name(id='foo', ctx=ast.Load()),
            attr='get_a_thing',
            ctx=ast.Load(),
        )
    ) 
Example 37
Project: miniast   Author: cpcloud   File: test_miniast.py    Apache License 2.0 5 votes vote down vote up
def test_sub(i):
    assert eq(
        var.a[i],
        ast.Subscript(
            value=ast.Name(id='a', ctx=ast.Load()),
            slice=ast.Index(value=ast.Num(n=i)),
            ctx=ast.Load()
        )
    ) 
Example 38
Project: py   Author: pytest-dev   File: _assertionnew.py    MIT License 5 votes vote down vote up
def visit_Attribute(self, attr):
        if not isinstance(attr.ctx, ast.Load):
            return self.generic_visit(attr)
        source_explanation, source_result = self.visit(attr.value)
        explanation = "%s.%s" % (source_explanation, attr.attr)
        source = "__exprinfo_expr.%s" % (attr.attr,)
        co = self._compile(source)
        try:
            result = self.frame.eval(co, __exprinfo_expr=source_result)
        except Exception:
            raise Failure(explanation)
        explanation = "%s\n{%s = %s.%s\n}" % (self.frame.repr(result),
                                              self.frame.repr(result),
                                              source_explanation, attr.attr)
        # Check if the attr is from an instance.
        source = "%r in getattr(__exprinfo_expr, '__dict__', {})"
        source = source % (attr.attr,)
        co = self._compile(source)
        try:
            from_instance = self.frame.eval(co, __exprinfo_expr=source_result)
        except Exception:
            from_instance = True
        if from_instance:
            rep = self.frame.repr(result)
            pattern = "%s\n{%s = %s\n}"
            explanation = pattern % (rep, rep, explanation)
        return explanation, result 
Example 39
Project: py   Author: pytest-dev   File: _assertionnew.py    MIT License 5 votes vote down vote up
def visit_Assign(self, assign):
        value_explanation, value_result = self.visit(assign.value)
        explanation = "... = %s" % (value_explanation,)
        name = ast.Name("__exprinfo_expr", ast.Load(),
                        lineno=assign.value.lineno,
                        col_offset=assign.value.col_offset)
        new_assign = ast.Assign(assign.targets, name, lineno=assign.lineno,
                                col_offset=assign.col_offset)
        mod = ast.Module([new_assign])
        co = self._compile(mod, "exec")
        try:
            self.frame.exec_(co, __exprinfo_expr=value_result)
        except Exception:
            raise Failure(explanation)
        return explanation, value_result 
Example 40
Project: instaloader   Author: instaloader   File: __main__.py    MIT License 5 votes vote down vote up
def filterstr_to_filterfunc(filter_str: str, item_type: type):
    """Takes an --post-filter=... or --storyitem-filter=... filter
     specification and makes a filter_func Callable out of it."""

    # The filter_str is parsed, then all names occurring in its AST are replaced by loads to post.<name>. A
    # function Post->bool is returned which evaluates the filter with the post as 'post' in its namespace.

    class TransformFilterAst(ast.NodeTransformer):
        def visit_Name(self, node: ast.Name):
            # pylint:disable=no-self-use
            if not isinstance(node.ctx, ast.Load):
                raise InvalidArgumentException("Invalid filter: Modifying variables ({}) not allowed.".format(node.id))
            if node.id == "datetime":
                return node
            if not hasattr(item_type, node.id):
                raise InvalidArgumentException("Invalid filter: {} not a {} attribute.".format(node.id,
                                                                                               item_type.__name__))
            new_node = ast.Attribute(ast.copy_location(ast.Name('item', ast.Load()), node), node.id,
                                     ast.copy_location(ast.Load(), node))
            return ast.copy_location(new_node, node)

    input_filename = '<command line filter parameter>'
    compiled_filter = compile(TransformFilterAst().visit(ast.parse(filter_str, filename=input_filename, mode='eval')),
                              filename=input_filename, mode='eval')

    def filterfunc(item) -> bool:
        # pylint:disable=eval-used
        return bool(eval(compiled_filter, {'item': item, 'datetime': datetime.datetime}))

    return filterfunc 
Example 41
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_identitifer(self):
        m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
        ast.fix_missing_locations(m)
        with self.assertRaises(TypeError) as cm:
            compile(m, "<test>", "exec")
        self.assertIn("identifier must be of type str", str(cm.exception)) 
Example 42
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.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')], [])))
        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=[], "
            "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=[], lineno=1, "
            "col_offset=0), lineno=1, col_offset=0)])"
        ) 
Example 43
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_module(self):
        m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
        self.mod(m, "must have Load context", "single")
        m = ast.Expression(ast.Name("x", ast.Store()))
        self.mod(m, "must have Load context", "eval") 
Example 44
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def _check_arguments(self, fac, check):
        def arguments(args=None, vararg=None,
                      kwonlyargs=None, kwarg=None,
                      defaults=None, kw_defaults=None):
            if args is None:
                args = []
            if kwonlyargs is None:
                kwonlyargs = []
            if defaults is None:
                defaults = []
            if kw_defaults is None:
                kw_defaults = []
            args = ast.arguments(args, vararg, kwonlyargs, kw_defaults,
                                 kwarg, defaults)
            return fac(args)
        args = [ast.arg("x", ast.Name("x", ast.Store()))]
        check(arguments(args=args), "must have Load context")
        check(arguments(kwonlyargs=args), "must have Load context")
        check(arguments(defaults=[ast.Num(3)]),
                       "more positional defaults than args")
        check(arguments(kw_defaults=[ast.Num(4)]),
                       "length of kwonlyargs is not the same as kw_defaults")
        args = [ast.arg("x", ast.Name("x", ast.Load()))]
        check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
                       "must have Load context")
        args = [ast.arg("a", ast.Name("x", ast.Load())),
                ast.arg("b", ast.Name("y", ast.Load()))]
        check(arguments(kwonlyargs=args,
                          kw_defaults=[None, ast.Name("x", ast.Store())]),
                          "must have Load context") 
Example 45
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_delete(self):
        self.stmt(ast.Delete([]), "empty targets on Delete")
        self.stmt(ast.Delete([None]), "None disallowed")
        self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
                  "must have Del context") 
Example 46
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_assign(self):
        self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
        self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
        self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
                  "must have Store context")
        self.stmt(ast.Assign([ast.Name("x", ast.Store())],
                                ast.Name("y", ast.Store())),
                  "must have Load context") 
Example 47
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_augassign(self):
        aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
                            ast.Name("y", ast.Load()))
        self.stmt(aug, "must have Store context")
        aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
                            ast.Name("y", ast.Store()))
        self.stmt(aug, "must have Load context") 
Example 48
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_for(self):
        x = ast.Name("x", ast.Store())
        y = ast.Name("y", ast.Load())
        p = ast.Pass()
        self.stmt(ast.For(x, y, [], []), "empty body on For")
        self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
                  "must have Store context")
        self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
                  "must have Load context")
        e = ast.Expr(ast.Name("x", ast.Store()))
        self.stmt(ast.For(x, y, [e], []), "must have Load context")
        self.stmt(ast.For(x, y, [p], [e]), "must have Load context") 
Example 49
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_if(self):
        self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
        i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
        self.stmt(i, "must have Load context")
        i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
        self.stmt(i, "must have Load context")
        i = ast.If(ast.Num(3), [ast.Pass()],
                   [ast.Expr(ast.Name("x", ast.Store()))])
        self.stmt(i, "must have Load context") 
Example 50
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    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 51
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_raise(self):
        r = ast.Raise(None, ast.Num(3))
        self.stmt(r, "Raise with cause but no exception")
        r = ast.Raise(ast.Name("x", ast.Store()), None)
        self.stmt(r, "must have Load context")
        r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
        self.stmt(r, "must have Load context") 
Example 52
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_assert(self):
        self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
                  "must have Load context")
        assrt = ast.Assert(ast.Name("x", ast.Load()),
                           ast.Name("y", ast.Store()))
        self.stmt(assrt, "must have Load context") 
Example 53
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_boolop(self):
        b = ast.BoolOp(ast.And(), [])
        self.expr(b, "less than 2 values")
        b = ast.BoolOp(ast.And(), [ast.Num(3)])
        self.expr(b, "less than 2 values")
        b = ast.BoolOp(ast.And(), [ast.Num(4), None])
        self.expr(b, "None disallowed")
        b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
        self.expr(b, "must have Load context") 
Example 54
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_unaryop(self):
        u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
        self.expr(u, "must have Load context") 
Example 55
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    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 56
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_ifexp(self):
        l = ast.Name("x", ast.Load())
        s = ast.Name("y", ast.Store())
        for args in (s, l, l), (l, s, l), (l, l, s):
            self.expr(ast.IfExp(*args), "must have Load context") 
Example 57
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_dict(self):
        d = ast.Dict([], [ast.Name("x", ast.Load())])
        self.expr(d, "same number of keys as values")
        d = ast.Dict([ast.Name("x", ast.Load())], [None])
        self.expr(d, "None disallowed") 
Example 58
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def _check_comprehension(self, fac):
        self.expr(fac([]), "comprehension with no generators")
        g = ast.comprehension(ast.Name("x", ast.Load()),
                              ast.Name("x", ast.Load()), [], 0)
        self.expr(fac([g]), "must have Store context")
        g = ast.comprehension(ast.Name("x", ast.Store()),
                              ast.Name("x", ast.Store()), [], 0)
        self.expr(fac([g]), "must have Load context")
        x = ast.Name("x", ast.Store())
        y = ast.Name("y", ast.Load())
        g = ast.comprehension(x, y, [None], 0)
        self.expr(fac([g]), "None disallowed")
        g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
        self.expr(fac([g]), "must have Load context") 
Example 59
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def _simple_comp(self, fac):
        g = ast.comprehension(ast.Name("x", ast.Store()),
                              ast.Name("x", ast.Load()), [], 0)
        self.expr(fac(ast.Name("x", ast.Store()), [g]),
                  "must have Load context")
        def wrap(gens):
            return fac(ast.Name("x", ast.Store()), gens)
        self._check_comprehension(wrap) 
Example 60
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_dictcomp(self):
        g = ast.comprehension(ast.Name("y", ast.Store()),
                              ast.Name("p", ast.Load()), [], 0)
        c = ast.DictComp(ast.Name("x", ast.Store()),
                         ast.Name("y", ast.Load()), [g])
        self.expr(c, "must have Load context")
        c = ast.DictComp(ast.Name("x", ast.Load()),
                         ast.Name("y", ast.Store()), [g])
        self.expr(c, "must have Load context")
        def factory(comps):
            k = ast.Name("x", ast.Load())
            v = ast.Name("y", ast.Load())
            return ast.DictComp(k, v, comps)
        self._check_comprehension(factory) 
Example 61
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_yield(self):
        self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
        self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load") 
Example 62
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_compare(self):
        left = ast.Name("x", ast.Load())
        comp = ast.Compare(left, [ast.In()], [])
        self.expr(comp, "no comparators")
        comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
        self.expr(comp, "different number of comparators and operands")
        comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
        self.expr(comp, "non-numeric", exc=TypeError)
        comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
        self.expr(comp, "non-numeric", exc=TypeError) 
Example 63
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_attribute(self):
        attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
        self.expr(attr, "must have Load context") 
Example 64
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_starred(self):
        left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
                        ast.Store())
        assign = ast.Assign([left], ast.Num(4))
        self.stmt(assign, "must have Store context") 
Example 65
Project: NiujiaoDebugger   Author: MrSrc   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def _sequence(self, fac):
        self.expr(fac([None], ast.Load()), "None disallowed")
        self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
                  "must have Load context") 
Example 66
Project: europython2018   Author: pythoninside   File: 11-ast.py    GNU General Public License v3.0 5 votes vote down vote up
def visit_ClassDef(self, node):
        # Only decorate classes with type annotations
        if [True for n in node.body if isinstance(n, ast.AnnAssign)]:
            dec = ast.Name(id='dataclass', ctx=ast.Load())
            node.decorator_list.insert(0, dec)
            dec = ast.Name(id='type_check', ctx=ast.Load())
            node.decorator_list.insert(0, dec)
        return node 
Example 67
Project: europython2018   Author: pythoninside   File: 10-interlude_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def visit_Str(self, node):
        # Replace each string with a call to <string>.upper()
        new_node = ast.Call(
            func=ast.Attribute(value=node, attr='upper', ctx=ast.Load()),
            args=[],
            keywords=[])
        return new_node 
Example 68
Project: YAPyPy   Author: Xython   File: symbol_analyzer.py    MIT License 5 votes vote down vote up
def _visit_name(self, node: ast.Name):
    symtable = self.symtable
    name = node.id
    if isinstance(node.ctx, ast.Store):
        symtable.entered.add(name)
    elif isinstance(node.ctx, ast.Load):
        symtable.requires.add(name)
    return node 
Example 69
Project: YAPyPy   Author: Xython   File: helper.py    MIT License 5 votes vote down vote up
def atom_rewrite(loc, name, token, value, number, strs, namedc, ellipsis, dict, is_dict,
                 is_gen, is_list, comp, yield_expr):
    if name:
        if not token:
            return ast.Name(name.value, ast.Load(), **loc @ name)
        return ex_ast.AssignExpr(
            ast.Name(name.value, ast.Store(), **loc @ name), value=value, **loc @ token)

    if number:
        return ast.Num(eval(number.value), **loc @ number)

    if strs:
        return str_maker(*strs)

    if ellipsis:
        return ast.Ellipsis()

    if namedc:
        return ast.NameConstant(eval(namedc.value), **loc @ namedc)

    if is_dict:
        return dict or ex_ast.ExDict([], [], ast.Load(), **loc @ is_dict)

    if is_gen:
        if yield_expr:
            return yield_expr
        return comp(is_tuple=True) if comp else ast.Tuple([], ast.Load(), **loc @ is_gen)

    if is_list:
        return comp(is_list=True) if comp else ast.List([], ast.Load(), **loc @ is_list)

    raise TypeError 
Example 70
Project: Alexa-Ecovacs   Author: EtienneMD   File: rewrite.py    MIT License 5 votes vote down vote up
def _NameConstant(c):
        return ast.Name(str(c), ast.Load()) 
Example 71
Project: Alexa-Ecovacs   Author: EtienneMD   File: rewrite.py    MIT License 5 votes vote down vote up
def assign(self, expr):
        """Give *expr* a name."""
        name = self.variable()
        self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))
        return ast.Name(name, ast.Load()) 
Example 72
Project: Alexa-Ecovacs   Author: EtienneMD   File: rewrite.py    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 73
Project: Alexa-Ecovacs   Author: EtienneMD   File: rewrite.py    MIT License 5 votes vote down vote up
def builtin(self, name):
        """Return the builtin called *name*."""
        builtin_name = ast.Name("@py_builtins", ast.Load())
        return ast.Attribute(builtin_name, name, ast.Load()) 
Example 74
Project: Alexa-Ecovacs   Author: EtienneMD   File: rewrite.py    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.on_failure
        levels = len(boolop.values) - 1
        self.push_format_context()
        # Process each operand, short-circuting if needed.
        for i, v in enumerate(boolop.values):
            if i:
                fail_inner = []
                # cond is set in a prior loop iteration below
                self.on_failure.append(ast.If(cond, fail_inner, []))  # noqa
                self.on_failure = 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.on_failure.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.on_failure = 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 75
Project: Alexa-Ecovacs   Author: EtienneMD   File: rewrite.py    MIT License 5 votes vote down vote up
def visit_Attribute(self, attr):
        if not isinstance(attr.ctx, ast.Load):
            return self.generic_visit(attr)
        value, value_expl = self.visit(attr.value)
        res = self.assign(ast.Attribute(value, attr.attr, ast.Load()))
        res_expl = self.explanation_param(self.display(res))
        pat = "%s\n{%s = %s.%s\n}"
        expl = pat % (res_expl, res_expl, value_expl, attr.attr)
        return res, expl 
Example 76
Project: Alexa-Ecovacs   Author: EtienneMD   File: rewrite.py    MIT License 5 votes vote down vote up
def visit_Compare(self, comp):
        self.push_format_context()
        left_res, left_expl = self.visit(comp.left)
        if isinstance(comp.left, (ast.Compare, ast.BoolOp)):
            left_expl = "({0})".format(left_expl)
        res_variables = [self.variable() for i in range(len(comp.ops))]
        load_names = [ast.Name(v, ast.Load()) for v in res_variables]
        store_names = [ast.Name(v, ast.Store()) for v in res_variables]
        it = zip(range(len(comp.ops)), comp.ops, comp.comparators)
        expls = []
        syms = []
        results = [left_res]
        for i, op, next_operand in it:
            next_res, next_expl = self.visit(next_operand)
            if isinstance(next_operand, (ast.Compare, ast.BoolOp)):
                next_expl = "({0})".format(next_expl)
            results.append(next_res)
            sym = binop_map[op.__class__]
            syms.append(ast.Str(sym))
            expl = "%s %s %s" % (left_expl, sym, next_expl)
            expls.append(ast.Str(expl))
            res_expr = ast.Compare(left_res, [op], [next_res])
            self.statements.append(ast.Assign([store_names[i]], res_expr))
            left_res, left_expl = next_res, next_expl
        # Use pytest.assertion.util._reprcompare if that's available.
        expl_call = self.helper("call_reprcompare",
                                ast.Tuple(syms, ast.Load()),
                                ast.Tuple(load_names, ast.Load()),
                                ast.Tuple(expls, ast.Load()),
                                ast.Tuple(results, ast.Load()))
        if len(comp.ops) > 1:
            res = ast.BoolOp(ast.And(), load_names)
        else:
            res = load_names[0]
        return res, self.explanation_param(self.pop_format_context(expl_call)) 
Example 77
Project: Alexa-Ecovacs   Author: EtienneMD   File: _assertionnew.py    MIT License 5 votes vote down vote up
def visit_Attribute(self, attr):
        if not isinstance(attr.ctx, ast.Load):
            return self.generic_visit(attr)
        source_explanation, source_result = self.visit(attr.value)
        explanation = "%s.%s" % (source_explanation, attr.attr)
        source = "__exprinfo_expr.%s" % (attr.attr,)
        co = self._compile(source)
        try:
            result = self.frame.eval(co, __exprinfo_expr=source_result)
        except Exception:
            raise Failure(explanation)
        explanation = "%s\n{%s = %s.%s\n}" % (self.frame.repr(result),
                                              self.frame.repr(result),
                                              source_explanation, attr.attr)
        # Check if the attr is from an instance.
        source = "%r in getattr(__exprinfo_expr, '__dict__', {})"
        source = source % (attr.attr,)
        co = self._compile(source)
        try:
            from_instance = self.frame.eval(co, __exprinfo_expr=source_result)
        except Exception:
            from_instance = True
        if from_instance:
            rep = self.frame.repr(result)
            pattern = "%s\n{%s = %s\n}"
            explanation = pattern % (rep, rep, explanation)
        return explanation, result 
Example 78
Project: Alexa-Ecovacs   Author: EtienneMD   File: _assertionnew.py    MIT License 5 votes vote down vote up
def visit_Assign(self, assign):
        value_explanation, value_result = self.visit(assign.value)
        explanation = "... = %s" % (value_explanation,)
        name = ast.Name("__exprinfo_expr", ast.Load(),
                        lineno=assign.value.lineno,
                        col_offset=assign.value.col_offset)
        new_assign = ast.Assign(assign.targets, name, lineno=assign.lineno,
                                col_offset=assign.col_offset)
        mod = ast.Module([new_assign])
        co = self._compile(mod, "exec")
        try:
            self.frame.exec_(co, __exprinfo_expr=value_result)
        except Exception:
            raise Failure(explanation)
        return explanation, value_result 
Example 79
Project: smp_graphs   Author: x75   File: common.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def visit_Assign(self, node):
        # print "node.targets", node.targets
        if isinstance(node.targets[0], ast.Name):
            # print "Found Name", type(node.targets[0].id), node.targets[0].id
            if node.targets[0].id == 'lconf' and self.lconf is not None:
                # print "founde lconf", type(node.targets[0].id), node.targets[0].id
                # print "lconf", type(self.lconf)
                lconf_parsed = ast.parse(str(self.lconf), '<string>', 'exec')
                # print "lconf_parsed", lconf_parsed.body[0].value
                # print "lconf_old", node.value
                # lconf_parsed = ast.fix_missing_locations(lconf_parsed)
                # print "node.value", type(node.value)
                # print "node.value", node.value._attributes
                # print "node.value", node.value._fields
                # print "node.value", node.value.keys
                # print "node.value", node.value.values

                # # print debugging ast objects
                # for k, v in zip(node.value.keys, node.value.values):
                #     # print "dir(k)", dir(k)
                #     # print "dir(v)", dir(v)
                #     print "node.value old",
                #     if hasattr(k, 's'):
                #         print "k = %s" % (k.s, ),
                #     if hasattr(v, 'n'):
                #         print "v = %s" % (v.n, ),
                #     print ""
                    
                # for k, v in zip(lconf_parsed.body[0].value.keys, lconf_parsed.body[0].value.values):
                #     # print "dir(k)", dir(k)
                #     # print "dir(v)", dir(v)
                #     print "node.value new",
                #     if hasattr(k, 's'):
                #         print "k = %s" % (k.s, ),
                #     if hasattr(v, 'n'):
                #         print "v = %s" % (v.n, ),
                #     print ""
                    
                node.value = lconf_parsed.body[0].value
                # node = ast.fix_missing_locations(node)
                # print "node", node.lineno, lconf_parsed.body[0].value.lineno
                # return node
        #         # swap old for parsed
        # return ast.copy_location(ast.Subscript(
        #     value=ast.Assign(id='data', ctx=ast.Load()),
        #     slice=ast.Index(value=ast.Str(s=node.id)),
        #     ctx=node.ctx
        # ), node)
        return node 
Example 80
Project: resolwe   Author: genialis   File: parser.py    Apache License 2.0 4 votes vote down vote up
def visit_ClassDef(self, node):  # pylint: disable=invalid-name
        """Visit top-level classes."""
        # Resolve everything as root scope contains everything from the process module.
        for base in node.bases:
            # Cover `from resolwe.process import ...`.
            if isinstance(base, ast.Name) and isinstance(base.ctx, ast.Load):
                base = getattr(runtime, base.id, None)
            # Cover `from resolwe import process`.
            elif isinstance(base, ast.Attribute) and isinstance(base.ctx, ast.Load):
                base = getattr(runtime, base.attr, None)
            else:
                continue

            if issubclass(base, runtime.Process):
                break
        else:
            return

        descriptor = ProcessDescriptor(source=self.source)

        # Available embedded classes.
        embedded_class_fields = {
            runtime.PROCESS_INPUTS_NAME: descriptor.inputs,
            runtime.PROCESS_OUTPUTS_NAME: descriptor.outputs,
        }

        # Parse metadata in class body.
        for item in node.body:
            if isinstance(item, ast.Assign):
                # Possible metadata.
                if (len(item.targets) == 1 and isinstance(item.targets[0], ast.Name)
                        and isinstance(item.targets[0].ctx, ast.Store)
                        and item.targets[0].id in PROCESS_METADATA):
                    # Try to get the metadata value.
                    value = PROCESS_METADATA[item.targets[0].id].get_value(item.value)
                    setattr(descriptor.metadata, item.targets[0].id, value)
            elif (isinstance(item, ast.Expr) and isinstance(item.value, ast.Str)
                  and descriptor.metadata.description is None):
                # Possible description string.
                descriptor.metadata.description = item.value.s
            elif isinstance(item, ast.ClassDef) and item.name in embedded_class_fields.keys():
                # Possible input/output declaration.
                self.visit_field_class(item, descriptor, embedded_class_fields[item.name])

        descriptor.validate()
        self.processes.append(descriptor)