减少Python代码生成中嵌套函数的缩进

2024-04-23 11:53:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是动态生成函数,然后将它们保存在文件中。例如,在我当前的尝试中,调用create_file

import io


def create_file():
    nested_func = make_nested_func()
    write_to_file([nested_func, a_root_func], '/tmp/code.py')


def a_root_func(x):
    pass


def make_nested_func():
    def a_nested_func(b, k):
        return b, k

    return a_nested_func


def write_to_file(code_list, path):
    import inspect
    code_str_list = [inspect.getsource(c) for c in code_list]
    with open(path, 'w') as ofh:
        for c in code_str_list:
            fh = io.StringIO(c)
            ofh.writelines(fh.readlines())
            ofh.write('\n')


create_file()

我想要的输出是('/tmp/代码.py'):

^{pr2}$

我得到的输出是('/tmp/代码.py'):

    def a_nested_func(b, k):
        return b, k

def a_root_func(x):
    pass

a_nested_func缩进。如何减少压痕?我可以做lstrip等等,但是我想知道有没有更好的方法。在


Tags: pyioimportreturndefcreatecoderoot
2条回答

使用^{} function删除常见的前导空格:

import inspect
from textwrap import dedent

def write_to_file(code_list, path):
    code_str_list = [inspect.getsource(c) for c in code_list]
    with open(path, 'w') as ofh:
        for c in code_str_list:
            dedented = dedent(c)
            ofh.write(dedented + '\n')

注意这里不需要跳StringIO(string).readlines()舞。在

内置模块中有一个函数,^{}。在

import textwrap
s = """
   abc
     def
"""
s2 = """
abc
  def
"""
assert textwrap.dedent(s) == s2

相关问题 更多 >