當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.increment_lineno方法代碼示例

本文整理匯總了Python中ast.increment_lineno方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.increment_lineno方法的具體用法?Python ast.increment_lineno怎麽用?Python ast.increment_lineno使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ast的用法示例。


在下文中一共展示了ast.increment_lineno方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_increment_lineno

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import increment_lineno [as 別名]
def test_increment_lineno(self):
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src, n=3), src)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        )
        # issue10869: do not increment lineno of root twice
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        ) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:18,代碼來源:test_ast.py

示例2: get_function_body_code

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import increment_lineno [as 別名]
def get_function_body_code(func):
    filename = inspect.getfile(func)
    func_body, line_offset = get_function_body(func)
    body_source = dedent_function_body(func_body)
    try:
        body_code = compile(body_source, filename, "exec", ast.PyCF_ONLY_AST)
        body_code = ast.increment_lineno(body_code, n=line_offset)
        body_code = compile(body_code, filename, "exec")
    except SyntaxError as e:
        if e.args[0] == "'return' outside function":
            filename, lineno, _, statement = e.args[1]
            raise SyntaxError(
                "No return statements allowed in ConfigScopes\n"
                "('{}' in File \"{}\", line {})".format(
                    statement.strip(), filename, lineno
                )
            )
        elif e.args[0] == "'yield' outside function":
            filename, lineno, _, statement = e.args[1]
            raise SyntaxError(
                "No yield statements allowed in ConfigScopes\n"
                "('{}' in File \"{}\", line {})".format(
                    statement.strip(), filename, lineno
                )
            )
        else:
            raise
    return body_code 
開發者ID:IDSIA,項目名稱:sacred,代碼行數:30,代碼來源:config_scope.py

示例3: __call__

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import increment_lineno [as 別名]
def __call__(self, function):  # pylint:disable=too-many-locals
        orig_lines, lineno = inspect.getsourcelines(function)
        indent_length = 0
        while orig_lines[1][indent_length] in [" ", "\t"]:
            indent_length += 1
        first_indent_length = indent_length
        setup_lines = 1
        while "):" not in orig_lines[setup_lines]:
            setup_lines += 1
        next_indented_idx = setup_lines + 1
        # get the next indented line
        while len(orig_lines[next_indented_idx]) <= indent_length + 1:
            next_indented_idx += 1
        while orig_lines[next_indented_idx][indent_length] in [" ", "\t"]:
            indent_length += 1
        second_indent = orig_lines[next_indented_idx][:indent_length]
        parse_lines = [second_indent + line + "\n"
                       for line in parse_varstring(self.string).split("\n")]
        parse_lines += [second_indent + '# (@parse_variables spacer line)\n']
        parse_lines += [second_indent + '# (setup spacer line)\n']*setup_lines
        # make ast of these new lines, insert it into the original ast
        new_lines = (orig_lines[1:setup_lines+1] + parse_lines
                     + orig_lines[setup_lines+1:])
        new_src = "\n".join([l[first_indent_length:-1] for l in new_lines
                             if "#" not in l[:first_indent_length]])
        new_ast = ast.parse(new_src, "<parse_variables>")
        ast.increment_lineno(new_ast, n=lineno-len(parse_lines))
        code = compile(new_ast, inspect.getsourcefile(function), "exec",
                       dont_inherit=True)  # don't inherit __future__ from here
        out = {}
        exec(code, self.scopevars, out)  # pylint: disable=exec-used
        return out[function.__name__] 
開發者ID:convexengineering,項目名稱:gpkit,代碼行數:34,代碼來源:docstring.py

示例4: parse_snippet

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import increment_lineno [as 別名]
def parse_snippet(source, filename, mode, flags, firstlineno):
    """ Like ast.parse, but accepts indented code snippet with a line number offset. """
    args = filename, mode, ast.PyCF_ONLY_AST, True
    prefix = '\n'
    try:
        a = compile(prefix + source, *args)
    except IndentationError:
        # Already indented? Wrap with dummy compound statement
        prefix = 'with 0:\n'
        a = compile(prefix + source, *args)
        # peel wrapper
        a.body = a.body[0].body
    ast.increment_lineno(a, firstlineno - 2)
    return a 
開發者ID:fastats,項目名稱:fastats,代碼行數:16,代碼來源:processor.py

示例5: wrap_code

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import increment_lineno [as 別名]
def wrap_code(code: str, args: str = '') -> ast.Module:
    """
    Compiles Python code into an async function or generator,
    and automatically adds return if the function body is a single evaluation.
    Also adds inline import expression support.
    """

    mod = import_expression.parse(CORO_CODE.format(args, textwrap.indent(code, ' ' * 8)), mode='exec')

    definition = mod.body[-1]  # async def ...:
    assert isinstance(definition, ast.AsyncFunctionDef)

    try_block = definition.body[-1]  # try:
    assert isinstance(try_block, ast.Try)

    ast.increment_lineno(mod, -16)  # bring line numbers back in sync with repl

    ast.fix_missing_locations(mod)

    KeywordTransformer().generic_visit(try_block)

    last_expr = try_block.body[-1]

    # if the last part isn't an expression, ignore it
    if not isinstance(last_expr, ast.Expr):
        return mod

    # if the last expression is not a yield
    if not isinstance(last_expr.value, ast.Yield):
        # copy the value of the expression into a yield
        yield_stmt = ast.Yield(last_expr.value)
        ast.copy_location(yield_stmt, last_expr)
        # place the yield into its own expression
        yield_expr = ast.Expr(yield_stmt)
        ast.copy_location(yield_expr, last_expr)

        # place the yield where the original expression was
        try_block.body[-1] = yield_expr

    return mod 
開發者ID:Gorialis,項目名稱:jishaku,代碼行數:42,代碼來源:compilation.py

示例6: test_increment_lineno

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import increment_lineno [as 別名]
def test_increment_lineno(self):
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src, n=3), src)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        ) 
開發者ID:ofermend,項目名稱:medicare-demo,代碼行數:10,代碼來源:test_ast.py

示例7: rewrite_assertion

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import increment_lineno [as 別名]
def rewrite_assertion(test: Test) -> Test:
    # Get the old code and code object
    code = inspect.getsource(test.fn)
    indents = textwrap._leading_whitespace_re.findall(code)
    col_offset = len(indents[0]) if len(indents) > 0 else 0
    code = textwrap.dedent(code)
    code_obj = test.fn.__code__

    # Rewrite the AST of the code
    tree = ast.parse(code)
    line_no = inspect.getsourcelines(test.fn)[1]
    ast.increment_lineno(tree, line_no - 1)

    new_tree = RewriteAssert().visit(tree)

    # We dedented the code so that it was a valid tree, now re-apply the indent
    for child in ast.walk(new_tree):
        if hasattr(child, "col_offset"):
            child.col_offset = getattr(child, "col_offset", 0) + col_offset

    # Reconstruct the test function
    new_mod_code_obj = compile(new_tree, code_obj.co_filename, "exec")

    # TODO: This probably isn't correct for nested closures
    clo_glob = {}
    if test.fn.__closure__:
        clo_glob = test.fn.__closure__[0].cell_contents.__globals__

    for const in new_mod_code_obj.co_consts:
        if isinstance(const, types.CodeType):
            new_test_func = types.FunctionType(
                const,
                {**assert_func_namespace, **test.fn.__globals__, **clo_glob},
                test.fn.__name__,
                test.fn.__defaults__,
            )
            new_test_func.ward_meta = test.fn.ward_meta
            return Test(
                **{k: vars(test)[k] for k in vars(test) if k != "fn"}, fn=new_test_func,
            )

    return test 
開發者ID:darrenburns,項目名稱:ward,代碼行數:44,代碼來源:rewrite.py


注:本文中的ast.increment_lineno方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。