Is there a way around coding in Python without the tab, indent & whitespace criteria?

前端 未结 29 1086
小鲜肉
小鲜肉 2020-12-31 14:05

I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of s

29条回答
  •  盖世英雄少女心
    2020-12-31 14:53

    Yes, there is a way. I hate these "no way" answers, there is no way until you discover one.

    And in that case, whatever it is worth, there is one.

    I read once about a guy who designed a way to code so that a simple script could re-indent the code properly. I didn't managed to find any links today, though, but I swear I read it.

    The main tricks are to always use return at the end of a function, always use pass at the end of an if or at the end of a class definition, and always use continue at the end of a while. Of course, any other no-effect instruction would fit the purpose.

    Then, a simple awk script can take your code and detect the end of block by reading pass/continue/return instructions, and the start of code with if/def/while/... instructions.

    Of course, because you'll develop your indenting script, you'll see that you don't have to use continue after a return inside the if, because the return will trigger the indent-back mechanism. The same applies for other situations. Just get use to it.

    If you are diligent, you'll be able to cut/paste and add/remove if and correct the indentations automagically. And incidentally, pasting code from the web will require you to understand a bit of it so that you can adapt it to that "non-classical" setting.

提交回复
热议问题