简体   繁体   English

Python代码中的奇怪缩进

[英]Strange indentation in Python code

I received some Python code to maintain. 我收到了一些Python代码来维护。 How can this possibly work and why it crashes with unindent error only if I modify the internals of the inner for loop? 只有当我修改内部for循环的内部时,它怎么可能工作以及为什么它会与unindent错误崩溃?

        for m in range(len(Model)):
        if param==1:
            m=m-1

            parFlag = 0
            for s in range(len(PSets)):
                if Parameter.lower() in self._Sets._P_ModelVars[Model[m]][PSets[s]]:
                    parFlag = 1

It looks even stranger now when I am entering it here: 当我在这里输入它时,它看起来更奇怪:

在此输入图像描述

I think it can have something to do with tabs, but I don't know much about them except I try to avoid them wherever possible. 我认为它可能与标签有关,但我不太了解它们,除非我尽可能避免它们。

Indeed, the code is mixing tabs and spaces: 实际上,代码混合了标签和空格:

>>> from pprint import pprint
>>> pprint('''\
...                     for m in range(len(Model)):
...                 if param==1:
...                     m=m-1
... 
...                 parFlag = 0
...                 for s in range(len(PSets)):
...                     if Parameter.lower() in self._Sets._P_ModelVars[Model[m]][PSets[s]]:
...                         parFlag = 1
... '''.splitlines())
['    \t\tfor m in range(len(Model)):',
 '\t\t    if param==1:',
 '\t\t    \tm=m-1',
 '',
 '        \t    parFlag = 0',
 '        \t    for s in range(len(PSets)):',
 '\t                if Parameter.lower() in self._Sets._P_ModelVars[Model[m]][PSets[s]]:',
 '\t                    parFlag = 1']

Note all the mix of \\t and 注意\\t\\t所有组合 characters at the start of each line. 每行开头的字符。

A good text editor will let you replace the tabs with spaces, and also let you set what style should be used when creating new indentations. 一个好的文本编辑器将允许您用空格替换选项卡,还可以设置创建新缩进时应使用的样式。 The Python style guide recommends you stick with only spaces. Python样式指南建议您只使用空格。

You can detect where spaces and tabs are mixed by running the code with the -tt command line switch: 您可以通过使用-tt命令行开关运行代码来检测空格和制表符的混合位置:

python -tt yourscript.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM