Skip to content

TabError: inconsistent use 的 tabs and 空间 in indentation

错误信息

                inconsistent use 的 tabs and 空间 in indentation
              

快速摘要

你的 file mixes tabs and 空间 for indentation in 方式那个 Python 能't unambiguously 解释执行.

为什么发生

  • Mixing tabs and 空间 in 相同块

  • 复制 code 从不同源 使用不同 indentation

  • Editor 设置更改之间 tab and 空间 indentation

最小示例

✗ 错误代码
if True:
	print('a')  # tab
    print('b')  # spaces  # TabError
✓ 修复代码
if True:
    print('a')  # 4 spaces
    print('b')  # 4 spaces

原始 mixes tab and 空间. Converting 所有 indentation 到 4 空间 resolves ambiguity.

如何诊断

  • Show whitespace characters in 你的 editor

  • 运行 'python -t file.py' 到 warn 关于 tabs and 空间

  • Use formatter 如 black 到 normalize indentation

如何修复

  • Convert 所有 tabs 到空间 (大多数 editors 有这个 option)

  • Use 仅空间 (4 每 level, 每 PEP 8) for indentation

  • 运行 'black file.py' 到 auto-格式 file

如何预防

  • 配置你的 editor 到 use 空间, 不 tabs

  • 设置 tab 宽度到 4 and 'insert 空间 for tabs'

  • Use formatter 如 black in 你的 workflow

相关资源

相关术语

相关课程

← 返回语言