如何修复Python缩进问题

301 投票
14 回答
367651 浏览
提问于 2025-04-15 12:24

我有一些Python代码,缩进不一致。代码中混用了很多制表符和空格,这让问题变得更复杂,甚至空格的缩进也没有保持一致。

虽然代码能正常运行,但维护起来很麻烦。

我该怎么修复这些缩进问题(就像HTML Tidy那样,但针对Python),而不破坏代码呢?


一些编辑器特定的建议:

14 个回答

61

如果你在使用Vim,可以查看:h retab

                                                        *:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
                        Replace all sequences of white-space containing a
                        <Tab> with new strings of white-space using the new
                        tabstop value given.  If you do not specify a new
                        tabstop size or it is zero, Vim uses the current value
                        of 'tabstop'.
                        The current value of 'tabstop' is always used to
                        compute the width of existing tabs.
                        With !, Vim also replaces strings of only normal
                        spaces with tabs where appropriate.
                        With 'expandtab' on, Vim replaces all tabs with the
                        appropriate number of spaces.
                        This command sets 'tabstop' to the new value given,
                        and if performed on the whole file, which is default,
                        should not make any visible change.
                        Careful: This command modifies any <Tab> characters
                        inside of strings in a C program.  Use "\t" to avoid
                        this (that's a good habit anyway).
                        ":retab!" may also change a sequence of spaces by
                        <Tab> characters, which can mess up a printf().
                        {not in Vi}
                        Not available when |+ex_extra| feature was disabled at
                        compile time.

比如说,如果你直接输入

:ret

那么你所有的制表符(Tab)都会被转换成空格。

你可能想要

:se et  " shorthand for :set expandtab

确保任何新行都不会使用实际的制表符。


如果你没有使用Vim,

perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py

会把制表符替换成空格,假设每8个字符是一个制表符停靠位置,处理的文件是file.py(原文件会备份为file.py.bak,以防万一)。如果你的制表符停靠位置是每4个空格,就把8改成4。

70

我会使用 autopep8 来完成这个任务:

$ # see what changes it would make
$ autopep8 path/to/file.py --select=E101,E121 --diff

$ # make these changes
$ autopep8 path/to/file.py --select=E101,E121 --in-place

注意:E101 和 E121 是关于pep8的缩进问题(我认为你可以简单地使用 --select=E1 来修复所有与缩进相关的问题 - 这些问题的编号都是以E1开头的)。

你可以使用递归标志将这个应用到整个项目:

$ autopep8 package_dir --recursive --select=E101,E121 --in-place

另见 将Python代码转换为符合PEP8规范的工具

303

使用你在 Python 安装目录下的 Tools/scripts/ 文件夹里找到的 reindent.py 脚本:

这个脚本可以把 Python (.py) 文件的缩进改成 4 个空格,并且不使用硬制表符。它还会去掉行末多余的空格和制表符,删除文件末尾的空行,并确保最后一行以换行符结束。

可以查看这个脚本,里面有详细的使用说明。


注意:如果你的 Linux 发行版默认没有安装 reindent:

很多 Linux 发行版在默认安装的 Python 中没有包含 reindent,一种简单的方法是使用 pip install reindent 来安装它。

另外,你也可以使用你发行版的包管理器(比如 apt-getyumdnf),但你需要找出哪个包里包含这个命令行工具,因为每个发行版的包名可能不同。

撰写回答