Python ast.Expr() Examples

The following are 30 code examples of ast.Expr(). 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: expression.py    From worker with GNU General Public License v3.0 7 votes vote down vote up
def compile_expression(exp):
    cached = cache.get(exp)
    if cached is not None:
        return cached
    _exp = ast.parse(exp)
    nodes = [node for node in ast.walk(_exp)]
    if len(nodes) < 2 or not isinstance(nodes[1], ast.Expr):
        raise ExpressionError("%s is not Expression" % exp)
    for node in nodes:
        if isinstance(node, ast.Call):
            raise ExpressionError("Call method is forbidden")
        if isinstance(node, ast.Lambda):
            raise ExpressionError("Lambda is strongly forbidden")
    result = compile(exp, '<string>', mode='eval')
    cache[exp] = result
    return result 
Example #2
Source File: test_ast.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_dump(self):
        node = ast.parse('spam(eggs, "and cheese")')
        self.assertEqual(ast.dump(node),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
            "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
            "keywords=[], starargs=None, kwargs=None))])"
        )
        self.assertEqual(ast.dump(node, annotate_fields=False),
            "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
            "Str('and cheese')], [], None, None))])"
        )
        self.assertEqual(ast.dump(node, include_attributes=True),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
            "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
            "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
            "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
            "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
        ) 
Example #3
Source File: test_ast.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_dump(self):
        node = ast.parse('spam(eggs, "and cheese")')
        self.assertEqual(ast.dump(node),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
            "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
            "keywords=[], starargs=None, kwargs=None))])"
        )
        self.assertEqual(ast.dump(node, annotate_fields=False),
            "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
            "Str('and cheese')], [], None, None))])"
        )
        self.assertEqual(ast.dump(node, include_attributes=True),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
            "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
            "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
            "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
            "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
        ) 
Example #4
Source File: test_ast.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_dump(self):
        node = ast.parse('spam(eggs, "and cheese")')
        self.assertEqual(ast.dump(node),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
            "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
            "keywords=[], starargs=None, kwargs=None))])"
        )
        self.assertEqual(ast.dump(node, annotate_fields=False),
            "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
            "Str('and cheese')], [], None, None))])"
        )
        self.assertEqual(ast.dump(node, include_attributes=True),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
            "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
            "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
            "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
            "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
        ) 
Example #5
Source File: _ast_to_ir2.py    From tmppy with Apache License 2.0 6 votes vote down vote up
def expression_stmt_to_ir2(stmt: ast.Expr, compilation_context: CompilationContext, next_stmt_line: int):
    expr = expression_ast_to_ir2(stmt.value,
                                 compilation_context,
                                 in_match_pattern=False,
                                 check_var_reference=lambda ast_node: None,
                                 match_lambda_argument_names=set(),
                                 current_stmt_line=stmt.lineno)

    lhs_var_name = next(compilation_context.identifier_generator)
    compilation_context.add_symbol(name=lhs_var_name,
                                   expr_type=expr.expr_type,
                                   definition_ast_node=stmt,
                                   is_only_partially_defined=False,
                                   is_function_that_may_throw=isinstance(expr.expr_type, ir2.FunctionType))

    return ir2.Assignment(lhs=ir2.VarReference(expr_type=expr.expr_type,
                                               name=lhs_var_name,
                                               is_global_function=False,
                                               is_function_that_may_throw=isinstance(expr.expr_type, ir2.FunctionType)),
                          rhs=expr,
                          source_branch=SourceBranch(compilation_context.filename,
                                                     stmt.lineno,
                                                     next_stmt_line)) 
Example #6
Source File: test_ast.py    From Fluid-Designer with 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 #7
Source File: github_increment_version.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def parse_setup():
    print("[1/8] | Parsing setup.py file")

    with open('setup.py', 'r') as f:
        file_contents = f.read()

    treeobj = ast.parse(file_contents, 'setup.py')

    setup_expression = None
    for element in treeobj.body:
        if isinstance(element, ast.Expr) and element.value.func.id == "setup":
            setup_expression = element

    if not setup_expression:
        print("No setup() found in setup.py")
        sys.exit(1)

    return file_contents, setup_expression 
Example #8
Source File: input.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CheckedEval(file_contents):
  """Return the eval of a gyp file.

  The gyp file is restricted to dictionaries and lists only, and
  repeated keys are not allowed.

  Note that this is slower than eval() is.
  """

  syntax_tree = ast.parse(file_contents)
  assert isinstance(syntax_tree, ast.Module)
  c1 = syntax_tree.body
  assert len(c1) == 1
  c2 = c1[0]
  assert isinstance(c2, ast.Expr)
  return CheckNode(c2.value, []) 
Example #9
Source File: PyAstFreeVariableAnalyses.py    From ufora with Apache License 2.0 6 votes vote down vote up
def _memberAccessChainWithLocImpl(pyAstNode):
    ''' Return a pair containing the access chain list and the root node.'''
    if isinstance(pyAstNode, ast.Name):
        return ([pyAstNode.id], pyAstNode)

    if isinstance(pyAstNode, ast.Expr):
        return _memberAccessChainWithLocImpl(pyAstNode.value)

    if isinstance(pyAstNode, ast.Attribute):
        # expr.attr: Attribute(expr value, identifier attr, expr_context context)
        (prefix, root) = _memberAccessChainWithLocImpl(pyAstNode.value)
        if len(prefix) == 0:
            return ([], None)  # return empty list for unexpected node-type

        prefix.append(pyAstNode.attr)
        return (prefix, root)

    return ([], None)  # return empty list for unexpected node-type 
Example #10
Source File: test_ast.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_dump(self):
        node = ast.parse('spam(eggs, "and cheese")')
        self.assertEqual(ast.dump(node),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
            "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
            "keywords=[], starargs=None, kwargs=None))])"
        )
        self.assertEqual(ast.dump(node, annotate_fields=False),
            "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
            "Str('and cheese')], [], None, None))])"
        )
        self.assertEqual(ast.dump(node, include_attributes=True),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
            "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
            "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
            "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
            "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
        ) 
Example #11
Source File: test_ast.py    From Fluid-Designer with 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 #12
Source File: node_transformers.py    From pynt with GNU General Public License v3.0 6 votes vote down vote up
def make_annotation(node=None, buffer='outside', content=None, cell_type='code', lineno=None):
    """Return a ast.Expr that looks like

    ```
    __cell__('make-cell', [content, buffer, cell_type])
    ```

    """
    content = astor.to_source(node).strip() if node else content
    lineno = str(node.lineno) if hasattr(node, 'lineno') else str(-1) if not lineno else str(lineno)
    call = ast.Call(
        func=ast.Name(id='__cell__', ctx=ast.Load()),
        args=[
            ast.Str(s=content),
            ast.Str(s=f'{buffer}'),
            ast.Str(s=cell_type),
            ast.Str(s=lineno),
        ],
        keywords=[]
    )
    return ast.Expr(call) 
Example #13
Source File: helper.py    From YAPyPy with MIT License 6 votes vote down vote up
def expr_stmt_rewrite(lhs, ann, aug, aug_exp, rhs: t.Optional[list]):
    if rhs:
        as_store(lhs)
        *init, end = rhs
        for each in init:
            as_store(each)
        return ast.Assign([lhs, *init], end)

    if ann:
        as_store(lhs)
        anno, value = ann
        return ast.AnnAssign(lhs, anno, value, 1)

    if aug_exp:
        as_store(lhs)
        return ast.AugAssign(lhs, aug(), aug_exp)

    # NO AS STORE HERE!
    return ast.Expr(lhs) 
Example #14
Source File: _toVerilog.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_FunctionDef(self, node):
        self.writeDoc(node)
        w = node.body[-1]
        y = w.body[0]
        if isinstance(y, ast.Expr):
            y = y.value
        assert isinstance(y, ast.Yield)
        self.writeAlwaysHeader()
        self.writeDeclarations()
        # assert isinstance(w.body, astNode.Stmt)
        for stmt in w.body[1:]:
            self.writeline()
            self.visit(stmt)
        self.dedent()
        self.writeline()
        self.write("end")
        self.writeline(2) 
Example #15
Source File: rule.py    From streamalert with Apache License 2.0 6 votes vote down vote up
def checksum(self):
        """Produce an md5 for the contents of this rule.

        This logic applies to expressions within the function only. It does not take
        into account: the function name, docstring, comments, or decorator arguments
        """
        if not self._checksum:
            try:
                code = inspect.getsource(self.func)
                root = ast.parse(code)
                md5 = hashlib.md5()  # nosec
                for expression in root.body[0].body:
                    # This check is necessary to ensure changes to the docstring
                    # are allowed without altering the checksum
                    if not isinstance(expression, ast.Expr):
                        md5.update(ast.dump(expression).encode('utf-8'))

                self._checksum = md5.hexdigest()
            except (TypeError, IndentationError, IndexError):
                LOGGER.exception('Could not checksum rule function')
                self._checksum = self.CHECKSUM_UNKNOWN

        return self._checksum 
Example #16
Source File: _parse_requirements.py    From pip-api with Apache License 2.0 6 votes vote down vote up
def _parse_local_package_name(path):
    """Tokenize setup.py and walk the syntax tree to find the package name"""
    try:
        with open(os.path.join(path, "setup.py")) as f:
            tree = ast.parse(f.read())
        setup_kwargs = [
            expr.value.keywords
            for expr in tree.body
            if isinstance(expr, ast.Expr)
            and isinstance(expr.value, ast.Call)
            and expr.value.func.id == "setup"
        ][0]
        value = [kw.value for kw in setup_kwargs if kw.arg == "name"][0]
        return value.s
    except (IndexError, AttributeError, IOError, OSError):
        raise PipError(
            "Directory %r is not installable. "
            "Could not parse package name from 'setup.py'." % path
        ) 
Example #17
Source File: _analyze.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_FunctionDef(self, node):
        self.refStack.push()
        for n in node.body:
            self.visit(n)
        self.tree.kind = _kind.SIMPLE_ALWAYS_COMB
        for n in node.body:
            if isinstance(n, ast.Expr) and isinstance(n.value, ast.Str):
                continue  # skip doc strings
            if isinstance(n, ast.Assign) and \
               isinstance(n.targets[0], ast.Attribute) and \
               self.getKind(n.targets[0].value) != _kind.REG:
                pass
            else:
                self.tree.kind = _kind.ALWAYS_COMB
                return
        # rom access is expanded into a case statement in addition
        # to any always_comb that contains a list of signals
        # if self.tree.hasRom or self.tree.hasLos:
        if self.tree.hasRom:
            self.tree.kind = _kind.ALWAYS_COMB
        self.refStack.pop() 
Example #18
Source File: _analyze.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_While(self, node):
        node.breakLabel = _Label("BREAK")
        node.loopLabel = _Label("LOOP")
        self.labelStack.append(node.breakLabel)
        self.labelStack.append(node.loopLabel)
        self.visit(node.test)
        self.refStack.push()
        for n in node.body:
            self.visit(n)
        self.refStack.pop()
        y = node.body[0]
        if isinstance(y, ast.Expr):
            y = y.value
        if node.test.obj == True and \
           isinstance(y, ast.Yield) and \
           not self.tree.hasYield > 1 and \
           not isinstance(self.getObj(y.value), delay):
            node.kind = _kind.ALWAYS
            self.tree.senslist = y.senslist
        self.require(node, not node.orelse, "while-else not supported")
        self.labelStack.pop()
        self.labelStack.pop() 
Example #19
Source File: routing.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def _prefix_names(src):
    """ast parse and prefix names with `.` to avoid collision with user vars"""
    tree = ast.parse(src).body[0]
    if isinstance(tree, ast.Expr):
        tree = tree.value
    for node in ast.walk(tree):
        if isinstance(node, ast.Name):
            node.id = "." + node.id
    return tree 
Example #20
Source File: execeval.py    From altair with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def eval_block(code, namespace=None, filename="<string>"):
    """
    Execute a multi-line block of code in the given namespace

    If the final statement in the code is an expression, return
    the result of the expression.
    """
    tree = ast.parse(code, filename="<ast>", mode="exec")
    if namespace is None:
        namespace = {}
    catch_display = _CatchDisplay()

    if isinstance(tree.body[-1], ast.Expr):
        to_exec, to_eval = tree.body[:-1], tree.body[-1:]
    else:
        to_exec, to_eval = tree.body, []

    for node in to_exec:
        compiled = compile(Module([node], []), filename=filename, mode="exec")
        exec(compiled, namespace)

    with catch_display:
        for node in to_eval:
            compiled = compile(
                ast.Interactive([node]), filename=filename, mode="single"
            )
            exec(compiled, namespace)

    return catch_display.output 
Example #21
Source File: node_visitor.py    From bandit with Apache License 2.0 5 votes vote down vote up
def visit_Str(self, node):
        '''Visitor for AST String nodes

        add relevant information about node to
        the context for use in tests which inspect strings.
        :param node: The node that is being inspected
        :return: -
        '''
        self.context['str'] = node.s
        if not isinstance(node._bandit_parent, ast.Expr):  # docstring
            self.context['linerange'] = b_utils.linerange_fix(
                node._bandit_parent
            )
            self.update_scores(self.tester.run_tests(self.context, 'Str')) 
Example #22
Source File: routing.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def _prefix_names(src):
    """ast parse and prefix names with `.` to avoid collision with user vars"""
    tree = ast.parse(src).body[0]
    if isinstance(tree, ast.Expr):
        tree = tree.value
    for node in ast.walk(tree):
        if isinstance(node, ast.Name):
            node.id = "." + node.id
    return tree 
Example #23
Source File: _imports.py    From deal with MIT License 5 votes vote down vote up
def _get_contracts(tree: ast.Module) -> List[ast.AST]:
        for node in tree.body:  # type: Any
            if type(node) is not ast.Expr:
                continue
            if type(node.value) is not ast.Call:
                continue
            if get_name(node.value.func) != 'deal.module_load':
                continue
            return node.value.args
        return [] 
Example #24
Source File: test_ast.py    From Fluid-Designer with 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 #25
Source File: test_assertrewrite.py    From pytest with MIT License 5 votes vote down vote up
def test_place_initial_imports(self):
        s = """'Doc string'\nother = stuff"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        for imp in m.body[1:3]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Assign)
        s = """from __future__ import division\nother_stuff"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.ImportFrom)
        for imp in m.body[1:3]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Expr)
        s = """'doc string'\nfrom __future__ import division"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        assert isinstance(m.body[1], ast.ImportFrom)
        for imp in m.body[2:4]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        s = """'doc string'\nfrom __future__ import division\nother"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        assert isinstance(m.body[1], ast.ImportFrom)
        for imp in m.body[2:4]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 3
            assert imp.col_offset == 0
        assert isinstance(m.body[4], ast.Expr)
        s = """from . import relative\nother_stuff"""
        m = rewrite(s)
        for imp in m.body[:2]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 1
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Expr) 
Example #26
Source File: rewrite.py    From pytest with MIT License 5 votes vote down vote up
def visit_BoolOp(self, boolop: ast.BoolOp) -> Tuple[ast.Name, str]:
        res_var = self.variable()
        expl_list = self.assign(ast.List([], ast.Load()))
        app = ast.Attribute(expl_list, "append", ast.Load())
        is_or = int(isinstance(boolop.op, ast.Or))
        body = save = self.statements
        fail_save = self.expl_stmts
        levels = len(boolop.values) - 1
        self.push_format_context()
        # Process each operand, short-circuiting if needed.
        for i, v in enumerate(boolop.values):
            if i:
                fail_inner = []  # type: List[ast.stmt]
                # cond is set in a prior loop iteration below
                self.expl_stmts.append(ast.If(cond, fail_inner, []))  # noqa
                self.expl_stmts = fail_inner
            self.push_format_context()
            res, expl = self.visit(v)
            body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
            expl_format = self.pop_format_context(ast.Str(expl))
            call = ast.Call(app, [expl_format], [])
            self.expl_stmts.append(ast.Expr(call))
            if i < levels:
                cond = res  # type: ast.expr
                if is_or:
                    cond = ast.UnaryOp(ast.Not(), cond)
                inner = []  # type: List[ast.stmt]
                self.statements.append(ast.If(cond, inner, []))
                self.statements = body = inner
        self.statements = save
        self.expl_stmts = fail_save
        expl_template = self.helper("_format_boolop", expl_list, ast.Num(is_or))
        expl = self.pop_format_context(expl_template)
        return ast.Name(res_var, ast.Load()), self.explanation_param(expl) 
Example #27
Source File: github_increment_version.py    From py-ipv8 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def parse_rest_manager():
    print("[1/8] | Parsing ipv8/REST/rest_manager.py file")

    with open('ipv8/REST/rest_manager.py', 'r') as f:
        file_contents = f.read()

    treeobj = ast.parse(file_contents, 'ipv8/REST/rest_manager.py')

    version_element = None
    for element in treeobj.body:
        if isinstance(element, ast.ClassDef) and element.name == "RESTManager":
            for inner_definition in element.body:
                if isinstance(inner_definition, ast.AsyncFunctionDef) and inner_definition.name == "start":
                    for f_statement in inner_definition.body:
                        if (isinstance(f_statement, ast.Expr)
                                and isinstance(f_statement.value, ast.Call)
                                and isinstance(f_statement.value.func, ast.Name)
                                and f_statement.value.func.id == "setup_aiohttp_apispec"):
                            for setup_arg in f_statement.value.keywords:
                                if setup_arg.arg == "version":
                                    version_element = setup_arg.value

    if not version_element:
        print("No 'version' assignment found in ipv8/REST/rest_manager.py")
        sys.exit(1)

    return file_contents, version_element 
Example #28
Source File: interpreter.py    From spidermon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check(self, expression):
        if not isinstance(expression, six.string_types):
            raise InvalidExpression("Python expressions must be defined as strings")
        if not expression:
            raise InvalidExpression("Empty python expression")

        try:
            tree = ast.parse(expression)
        except SyntaxError as e:
            raise e

        if not tree.body:
            raise InvalidExpression("Empty python expression")
        elif len(tree.body) > 1:
            raise InvalidExpression(
                "Python expressions must be a single line expression"
            )

        start_node = tree.body[0]
        if not isinstance(start_node, ast.Expr):
            raise InvalidExpression(
                "Python string must be an expression: '%s' found"
                % start_node.__class__.__name__
            )

        self._check_node(start_node) 
Example #29
Source File: BehavioralRTLIRGenL1Pass.py    From pymtl3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visit_Expr( s, node ):
    """Return the behavioral RTLIR of an expression.

    ast.Expr might be useful when a statement is only a call to a task or
    a non-returning function.
    """
    raise PyMTLSyntaxError(
      s.blk, node, 'Stand-alone expression is not supported yet!' ) 
Example #30
Source File: util.py    From training_results_v0.6 with Apache License 2.0 5 votes vote down vote up
def is_docstring(node):
    """Checks if a Python AST node is a docstring"""
    return isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)