Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: using 4 spaces for indentation. Why? [closed]

While coding python I'm using only 2 spaces to indent, sure PEP-8 really recommend to have 4 spaces, but historically for me it's unusual.

So, can anyone convince me to use 4 spaces instead of 2? What pros and cons?

P.S. And finally, what's easy way to convert all existing codebase from 2 spaces to 4 spaces?


P.P.S. PEP-8 Also srictly recommend not using tabs for indention. read here


So, to summarize:

Pros:

  • Have more space to arrange when wraping string more than 80 lines long.
  • Can copy code from snippets and it just works.

Cons:

  • With deeper level of nested statements you have less space for actual code.

Thanks.

like image 602
HardQuestions Avatar asked Jul 14 '09 14:07

HardQuestions


People also ask

Does Python only accept 4 spaces indentation?

Python doesn't care, as long as you're consistent. So if you start using four spaces for your indent, you always need to use four spaces. For example, in this snippet of code, we can see that the first indent has four spaces, but the second indent has only two. And you can see that the code doesn't line up.

Should I use tab or 4 spaces Python?

PEP-8 says 'Use 4 spaces per indentation level. ' Its clear that this is the standard recommendation. 'For really old code that you don't want to mess up, you can continue to use 8-space tabs.

Does Python require 4 spaces?

Note: Python uses 4 spaces as indentation by default. However, the number of spaces is up to you, but a minimum of 1 space has to be used.

How many spaces should be left for indentation?

Standard paragraph indentation is about five spaces or one-quarter to one-half of an inch, depending on which style guide you follow. In online writing, if your software doesn't allow indentation, insert a line space to indicate a new paragraph.


1 Answers

Everyone else uses 4 spaces. That is the only reason to use 4 spaces that I've come across and accepted. In my heart, I still want to use tabs (1 indent character per indent, makes sense, no? Separate indent from other whitespace. I don't care that tabs can be displayed as different widths, that makes no syntactic difference. The worst that can happen is that some of the comments don't line up. The horror!) but I've accepted that since the python community as a whole uses 4 spaces, I use 4 spaces. This way, I can assemble code from snippets others have written, and it all works.

like image 197
Markus Avatar answered Oct 06 '22 13:10

Markus