当前位置: 首页>>代码示例>>Python>>正文


Python astor.to_source方法代码示例

本文整理汇总了Python中astor.to_source方法的典型用法代码示例。如果您正苦于以下问题:Python astor.to_source方法的具体用法?Python astor.to_source怎么用?Python astor.to_source使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在astor的用法示例。


在下文中一共展示了astor.to_source方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: check_compiles

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def check_compiles(dsl_expr, code):
    types = ENV.__types__

    expr, functions = to_expr(dsl_expr)
    env = fn_types(functions)
    env.update(types['__root__'].__field_types__)

    expr = check(expr, types, env)

    # test eval
    lambda_expr = ExpressionCompiler.compile_lambda_expr(expr)
    eval(compile(lambda_expr, '<expr>', 'eval'))

    # test compile
    py_expr = ExpressionCompiler.compile_expr(expr)

    first = astor.to_source(py_expr).strip()
    second = dedent(code).strip()
    if first != second:
        msg = ('Compiled code is not equal:\n\n{}'
               .format('\n'.join(difflib.ndiff(first.splitlines(),
                                               second.splitlines()))))
        raise AssertionError(msg) 
开发者ID:vmagamedov,项目名称:hiku,代码行数:25,代码来源:test_compiler.py

示例2: exposed_astor_roundtrip_parser_functions

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def exposed_astor_roundtrip_parser_functions():
	'''
	Shove the feed-functions through the astor "round-trip"
	facility.

	Mostly, this homogenizes the indentation, and reformats the function.
	'''

	with db.session_context() as sess:
		res = sess.query(db.RssFeedEntry) \
			.all()

		for row in res:
			func = row.get_func()
			_ast = row._get_ast()
			src = astor.to_source(_ast, indent_with="	", pretty_source=better_pretty_source)

			if src.strip() != row.func.strip():
				try:
					rfdb.str_to_function(src, "testing_compile")
					print("Compiled OK")
					row.func = src
				except Exception:
					print("Compilation failed?")
		sess.commit() 
开发者ID:fake-name,项目名称:ReadableWebProxy,代码行数:27,代码来源:FeedDbManage.py

示例3: exposed_import_feed_parse_funcs

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def exposed_import_feed_parse_funcs():
	'''
	Import the feed parsing functions into the database.
	'''


	# parse_map = WebMirror.OutputFilters.rss.FeedDataParser.RSS_PARSE_FUNCTION_MAP
	# for key, func in parse_map.items():
	# 	func_str = astor.to_source(astor.code_to_ast(func), indent_with="	")
	# 	update_func(sess, key, func_str)

	name_map = WebMirror.OutputFilters.util.feedNameLut.mapper

	with common.database.session_context() as sess:
		for key, val in name_map.items():
			add_name(sess, key, val) 
开发者ID:fake-name,项目名称:ReadableWebProxy,代码行数:18,代码来源:FeedDbManage.py

示例4: get_source

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def get_source(self):
        """
        Get a string containing the Python source code corresponding to the
        statements in the block.

        Returns:
            A string containing the source code of the statements.
        """
        src = ""
        for statement in self.statements:
            if type(statement) in [ast.If, ast.For, ast.While]:
                src += (astor.to_source(statement)).split('\n')[0] + "\n"
            elif type(statement) == ast.FunctionDef or\
                 type(statement) == ast.AsyncFunctionDef:
                src += (astor.to_source(statement)).split('\n')[0] + "...\n"
            else:
                src += astor.to_source(statement)
        return src 
开发者ID:coetaur0,项目名称:staticfg,代码行数:20,代码来源:model.py

示例5: promote_loop

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def promote_loop(*region):
    """

    >>> code = '''
    ...
    ... for i in range(5):
    ...     for j in range(5):
    ...         k = i = j
    ...         print(k)
    ...
    ... '''

    """
    code, namespace = region
    tree = ast.parse(code)
    m = FirstPassForSimple(buffer=namespace).visit(tree)
    return astor.to_source(m) 
开发者ID:ebanner,项目名称:pynt,代码行数:19,代码来源:syntax.py

示例6: annotate_toplevel

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def annotate_toplevel(*region):
    """

    >>> code = '''
    ...
    ... for i in range(5):
    ...     for j in range(5):
    ...         k = i = j
    ...         print(k)
    ...
    ... '''
    >>> namespace = 'foo'
    >>> region = [code, namespace]

    """
    code, namespace = region
    tree = ast.parse(code)
    annotated_tree = Annotator(buffer=namespace).visit(tree)
    return astor.to_source(annotated_tree) 
开发者ID:ebanner,项目名称:pynt,代码行数:21,代码来源:syntax.py

示例7: unpack_annotations

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def unpack_annotations(annotations):
    """Extract the information out of a bunch of annotations

    >>> code = '''
    ...
    ... __cell__('`foo.baz`', 'foo.baz', '1', '9')
    ... __cell__('Arguments', 'foo.baz', '1', '-1')
    ... __cell__('Body', 'foo.baz', '1', '-1')
    ... __cell__('pass', 'foo.baz', 'code', '10')
    ...
    ... '''
    ...
    >>> annotations = ast.parse(code)

    """
    info = []
    m = astor.to_source(annotations)
    print(m)
    for annotation in annotations.body:
        content, namespace, cell_type, lineno = [arg.s for arg in annotation.value.args]
        info.append([content, namespace, cell_type, int(lineno)])
    return info 
开发者ID:ebanner,项目名称:pynt,代码行数:24,代码来源:syntax.py

示例8: test_filter_class

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def test_filter_class(self):
        code = """

class Foo:
    def bar():
        pass

class Bar:
    def biz():
        pass

"""
        tree = ast.parse(code)
        out = codebook.node_transformers.ClassFinder(class_name='Foo').visit(tree)
        c = astor.to_source(out)
        self.assertIn('Foo', c)
        self.assertNotIn('Bar', c) 
开发者ID:ebanner,项目名称:pynt,代码行数:19,代码来源:test_node_transformers.py

示例9: make_annotation

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
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) 
开发者ID:ebanner,项目名称:pynt,代码行数:23,代码来源:node_transformers.py

示例10: generic_visit

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def generic_visit(self, node):
        """Catch-all for nodes that slip through

        Basically everything I haven't gotten around to writing a custom
        annotator for gets caught here and wrapped in an annotation. Currently
        the one that jumps to mind are context managers.

        This is necessary because some nodes we recursively call `self.visit()`
        on and we may run into expressions that we have not written a node
        tranformer for.

        """
        # try:
        #     c = astor.to_source(node)
        #     print(c.strip())
        #     print(getattr(node, 'lineno', -1))
        #     print()
        # except:
        #     pass
        # return super().generic_visit(node)
        if not self.target_node and (getattr(node, 'lineno', -1) == self.lineno):
            self.target_node = node
        return super().generic_visit(node) 
开发者ID:ebanner,项目名称:pynt,代码行数:25,代码来源:node_transformers.py

示例11: parse_functions

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def parse_functions(code):
    """Parse all the global functions present in the input code.

    Parse all the ast nodes ast.FunctionDef that are global functions in the
    source code. These also include function that are defined inside other
    Python statements, like `try`. ast.ClassDef nodes are skipped from the
    parsing so that class functions are ignored.

    Args:
        code (str): Multiline string representing Python code

    Returns (dict): A dictionary [fn_name] -> function_source
    """
    fns = dict()
    tree = ast.parse(code)
    for block in tree.body:
        for node in walk(block,
                         stop_at=(ast.FunctionDef,),
                         ignore=(ast.ClassDef,)):
            if isinstance(node, (ast.FunctionDef,)):
                fn_name = node.name
                fns[fn_name] = astor.to_source(node)
    return fns 
开发者ID:kubeflow-kale,项目名称:kale,代码行数:25,代码来源:ast.py

示例12: ast_formatted_value

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def ast_formatted_value(
    val, fmt_str: str = None, conversion=None
) -> ast.FormattedValue:

    if astor.to_source(val)[0] == "{":
        raise FlyntException(
            "values starting with '{' are better left not transformed."
        )

    if fmt_str:
        format_spec = ast.JoinedStr([ast_string_node(fmt_str.replace(":", ""))])
    else:
        format_spec = None

    if conversion is None:
        conversion = -1
    else:
        conversion = ord(conversion.replace("!", ""))
    return ast.FormattedValue(value=val, conversion=conversion, format_spec=format_spec) 
开发者ID:ikamensh,项目名称:flynt,代码行数:21,代码来源:format_call_transforms.py

示例13: ast_formatted_value

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def ast_formatted_value(
    val, fmt_str: str = None, conversion=None
) -> ast.FormattedValue:
    if isinstance(val, ast.FormattedValue):
        return val

    if astor.to_source(val)[0] == "{":
        raise FlyntException(
            "values starting with '{' are better left not transformed."
        )

    if fmt_str:
        format_spec = ast.JoinedStr([ast_string_node(fmt_str.replace(":", ""))])
    else:
        format_spec = None

    if conversion is None:
        conversion = -1
    else:
        conversion = ord(conversion.replace("!", ""))
    return ast.FormattedValue(value=val, conversion=conversion, format_spec=format_spec) 
开发者ID:ikamensh,项目名称:flynt,代码行数:23,代码来源:transformer.py

示例14: transform_concat

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def transform_concat(code: str, *args, **kwargs) -> Tuple[str, bool]:
    tree = ast.parse(f"({code})")

    ft = ConcatTransformer()
    ft.visit(tree)
    il = FstrInliner()
    il.visit(tree)

    new_code = astor.to_source(tree)
    if new_code[-1] == "\n":
        new_code = new_code[:-1]

    new_code = new_code.replace("\n", "\\n")
    if new_code[:4] == 'f"""':
        new_code = set_quote_type(new_code, QuoteTypes.double)

    return new_code, ft.counter > 0 
开发者ID:ikamensh,项目名称:flynt,代码行数:19,代码来源:transformer.py

示例15: generate

# 需要导入模块: import astor [as 别名]
# 或者: from astor import to_source [as 别名]
def generate(module_name, code):
    """Generate search space.
    Return a serializable search space object.
    module_name: name of the module (str)
    code: user code (str)
    """
    try:
        ast_tree = ast.parse(code)
    except Exception:
        raise RuntimeError('Bad Python code')

    visitor = SearchSpaceGenerator(module_name)
    try:
        visitor.visit(ast_tree)
    except AssertionError as exc:
        raise RuntimeError('%d: %s' % (visitor.last_line, exc.args[0]))
    return visitor.search_space, astor.to_source(ast_tree) 
开发者ID:microsoft,项目名称:nni,代码行数:19,代码来源:search_space_generator.py


注:本文中的astor.to_source方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。