Use spaces or tabs only in python files?

In Python, is there a need to force spaces or tabbed tabs based on each file?

Well, perhaps the “coercion” is too strong, more like a “recommendation”.

I keep getting patch files with mixed indentation, and it's annoying ... (at least) Python itself can tell when there is a problem, but I'm looking for something for this at the editor level, for example, it exists for encoding.

Edit: Well, my question is not clear, I ask about it because I keep getting corrections and corrections in any tab / space combination that you can imagine. I use Mercurial as DVCS, maybe something exists at this level?

+4
source share
4 answers

Tim Peters wrote a great script called reindent.py that converts .py files to indent 4 spaces and without tabs. Available here , but check your distribution first - it can be included in the directory of examples or tools. (In the latest Ubuntu LTS, it is provided by the python2.7-examples package.)

If you can configure the Mercurial hook, you can run all the files through reindent.py.

By the way, if you use unix, your system may also have an expand (and unexpand ) unexpand that converts all tabs to spaces (and spaces to tabs). However, in this case, I think reindent.py is the right tool.

+10
source

Look at the tabnanny module: - detection of ambiguous indentation.

+5
source

This is what your editor should do for you. Most editors (try Notepad ++, for example, for free) will let you set whether tabs enter a tab or a space character. I would recommend using two spaces instead of tabs in all files (I believe this is too much). Using spaces instead of tabs is better since it means you can indent using both spaces and tab keys without worrying about messing up your files.

If you have mix files, it's easy to write your own script to convert tabs to spaces

+2
source

As shown in PEP 8 , never mix tabs and spaces. However, a file with both can run ... As they say there:

 The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended! 

Therefore, the solution should be used by default:

 python -t my_mixed_code.py 

To answer at the editor level, it depends on the editor, please indicate!

+2
source

Source: https://habr.com/ru/post/1304740/


All Articles