當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。