Tabs versus spaces in Python programming


Tabs versus spaces in Python programming



I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.



How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?



Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?





See also on programmers: Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?
– Deduplicator
Jul 19 '15 at 14:51




33 Answers
33



Because PEP-8 tells us to use spaces.





paxdiablo: Python doesn't know what your tabstop is set at, your file just puts in a tab character and your editor displays it however you tell it. The reason for always using 4 spaces is you can't reliably mix tabs. If you start a function using tabs and then finish with 4 spaces per indent, the interpreter thinks you've ended the function when it hits the transition. Since tabs and spaces are both invisible, this is non-obvious when you first encounter such an error, and you see a message complaining about unexpected indentation while it looks fine in your editor.
– bobpaul
Oct 13 '10 at 15:58





I can only hope too see a "new testament" where PEP-8 changed to recommend tabs instead of spaces.
– sorin
May 10 '11 at 9:34





@AramKocharyan, why doesn't really matter. There just needs to be an arbitrary choice, since you'll always get a possibility of confusion otherwise, when switching from one editor to another.
– Bruno
Oct 26 '12 at 12:49





PEP-8 was not intended for use by third-party projects. It's CPython's own internal style guide. Blindly following someone else's standards without understanding why those rules are in place won't produce better code.
– amcgregor
Jan 10 '13 at 20:36





@bobpaul That "reason" works just as well in reverse.
– kyrias
Mar 27 '13 at 15:49



Tired of chasing after indentation typos ( 8 spaces ? no, 7 oops 9 ... ) I switched my sources to 'tabs only'.



1 tab == 1 indent level, full stop



The point is: if you want to display the indentation as 4, 8 or pi / 12 character width, just change the settings in your text editor, don't mess with the code.



(Personally, I use 4 char width tab... but some would prefer 3 or 8 space, or even use variable width fonts.)





This is my preference too, but I’d love to hear a clear statement of the arguments against it. Is it that some editors don’t let their users decide how wide a tab stop should be? If so, um, hey programmers: get a better f—ing editor
– Paul D. Waite
Jan 27 '10 at 8:29





Or to put it another way: "A Tab" is meaningful. "A space" is not. It's meaning is dependent on the standard for that particular file. And considering that Python /relies/ on indentation levels, I tend to go with the one that explicitly indicates such: tabs.
– Ipsquiggle
Apr 9 '10 at 19:55





of course, if you're likely to have the off-by-one space indentation problem you speak of, you can still have it with tabs (by accidentally entering a space immediately before a tab). However, when this happens it's impossible to see. At least with all spaces things don't visually line up if you make a mistake. With tabs, a whitespace mistake can be invisible to the naked eye.
– Bryan Oakley
Apr 28 '10 at 17:38





@Bryan Oakley: But if you accidentally somehow insert a tab into your spaces the same will be true - the indentation will still be messed-up and you won't be able to see it. I think when indentation is as important as it is in python you should be able to see your indentation clearly and most editors can show them to you. @Ken: Always use a single tab for any additional indent (like inside brackets) and you're good. I don't approve alignment at all. This is not an ASCII art, it's code!
– inkredibl
Jul 19 '10 at 6:48





To me, this is very similar to the seperation of 'model' and 'view' in code, where here, the TAB is the model (i.e. 1 indentation level) and the VIEW is how it's rendered (by the editor as 4 spaces, or whatever). Using spaces is like trying to hard code view information into the model.
– Jarrett
Jan 18 '13 at 19:19



Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. -- Georg Brandl





The fallacy in this answer is that it implies that 4 spaces are an ideal solution. While certainly the most common / accepted indentation method, inserting 4 characters to represent one thing is a bit ridiculous when you think about it. My bet is that tabs will win in the long-term, just based on efficiency and simplicity.
– Steven Moseley
Jun 23 '13 at 11:24





Downvoters! Let me quote PEP-8 for you: "Use 4 spaces per indentation level".
– pillmuncher
Nov 22 '13 at 21:02






There's too much orthodoxy in software development, for too little sensible reason. Your answer is an example.
– shanusmagnus
Feb 27 '14 at 18:48





@shanusmagnus: You're right. There's too much orthodoxy. But my answer is not representative of that. It's a joke, based on a scene from a famous movie (from Monty Python, get it? Haha.) Also, in a language where so much depends on conventions, having this particular one allows everyone to move stuff around without having to worry too much about screwing up the formatting. Yes, I think orthodoxy should be challenged where needed. The four-spapces-indentation rule is just not challenge-worthy.
– pillmuncher
Feb 27 '14 at 19:53






@JürgenA.Erhard "Lost" implies you know for fact that the present represents the end-state of the conflict in question (tragically stereotypical judgement error). The future tense doesn't look to the status quo for direction. A good futurist analyzes the realm of possibility.
– Steven Moseley
Feb 10 '17 at 20:38



USE AN EDITOR THAT DISPLAYS TAB CHARACTERS (all whitespace, for that matter). You're programming, not writing an article.



I use tabs. There's no room for a one-space error in the tabs (if you can see them). The problem IS that people use different editors, and the only common thing in the world is: tab==indent, as above. Some bloke comes in with the tab key set to the wrong number of spaces or does it manually and makes a mess. TABs and use a real editor. (This isn't just contrary to the PEP, it's about C/C++ and other whitespace-agnostic languages too).



/steps down from soapbox





To argue the counterpoint: At my work, we are not allowed to view tabs/spaces. It is a waste of time and since we program in C#, spaces/tabs do not affect the logic/correctness. If we view them, we will become irritated and want to fix them. And my boss who pays for our time doesn't want to pay for that.
– Curtis Yallop
Mar 5 '14 at 17:08





People who used punched cards probably said something similar about vi. I'm guessing that's when spaces & tabs truly mattered
– Davos
Jun 17 '17 at 12:59





Showing whitespace may be too (visually) distracting.
– Peter Mortensen
Jul 3 at 3:28



My main reason for using tabs over spaces is the backspace key. If I'm on a line and I want to backspace-remove an indentation on just that one line I have to hit backspace 4x if it were spaces; whereas, I only need to hit it once if it's a tab.



I will continue to use tabs because—like was stated before—it's easier to convert from tabs to spaces, but not the other way around.



I'm thinking I want to write a simple program that converts code with spaces into code with tabs, because I freaking hate spaces. They drive me up the wall!



Oh! And using the arrow keys to navigate left and right is always a pain in the ass when it's spaces.



UPDATE: Sublime Text 3 now deletes a full soft tab with the backspace key; though, arrow-key navigation is still tedious.



UPDATE: See some cool animated GIFs that illustrate my points above and more at Tabs vs. Spaces, We Meet Again





If you are using linux, there is a program called unexpand which converts spaces to tabs. (expand converts tabs to spaces.)
– unutbu
Mar 5 '10 at 19:01


unexpand


expand





that sounds excellent, but alas! i'm not using linux. thanks for the tip though.
– jedmao
Mar 5 '10 at 19:09





A good text editor should do the work for you whatever your preferred choices are.
– Roberto Bonvallet
Mar 5 '10 at 19:11





I'm using Notepad++ for Python and it definitely allows me to do some spacing settings, but I still have the arrow-key and backspace navigation issues w/ spaces.
– jedmao
Mar 5 '10 at 19:14





vim (you're using vim, right?) in it's default python syntax mode, will delete a shiftwidth of spaces automatically.
– SingleNegationElimination
Jun 11 '11 at 2:16



The most "pythonic" way is to use 4 spaces per indentation level. The Python interpreter will however recognize spaces or tabs. The only gottcha is you must never mix spaces and tabs, pick one or the other. That said, the specification recommends spaces, most developers use spaces, so unless you have a really good reason not to, I'd say go with spaces.





There are plenty of very good reasons to use tabs; the question is: are there any really good reasons not to? And as far as I can tell the only one is "whoever wrote PEP-8 didn't like them" which seems a bit weak.
– Timmmm
Oct 19 '12 at 11:33





IMHO the big issue against tabs is code is often viewed or handled using multiple tools. (Not just "your favorite text editor"). Ex. you might view a git diff, email snippets of code, use web source viewing tools etc. Those will show a mess if the tab spacing doesn't match your editor.
– seand
May 24 '13 at 16:30





All good tools can configure the tab size in spaces : P
– Isaac Pascual
Nov 25 '16 at 11:48






"the big issue against tabs is code is often viewed or handled using multiple tools" --- Finding better tools is also an option.
– Daniel
Jun 15 '17 at 20:00





This is way a language should not be whitespace sensitive like this. Curly braces allow for auto indentation.
– Chris
Jun 16 '17 at 2:59



So far as I can tell, here are the pros and cons of tabs vs spaces.



Pros of tabs:



Cons of tabs:



There are some non-issues that are overblown by some people:



You might get stray spaces in tabbed indentation that screws things up: Virtually all IDEs/editors support visualising whitespace, and it's almost as likely that you'll get stray tabs in space indentations! I can't see this being a common error anyway. Besides, most indentation errors will be caught by Python, and good IDEs should be able to highlight different indentations.



You can't align things easily with tabs: This is true if you're going for character-perfect alignment, but PEP-8 recommends against this, and Python doesn't play well with multi-line statements anyway.



People have difference settings for tab display size in their editors so your code will look different in different places: Yeah, that's actually a beneficial feature of tabs.



I've started out using spaces to be consistent with other Python code, but to be honest it is frustrating enough that I will probably change back to tabs. A lot depends on the capabilities of your IDE, but in my experience no amount of IDE support for space indentation is as good as just using tabs.



So unless you really don't like being inconsistent with most (presumably not all!) Python code, use tabs and turn on whitespace visualisation and indentation highlighting (if available). The biggest reason for me is ease of selection and the (fairly significant IMO) reduction in keystrokes. Some conventions are stupid.





"I've started out using spaces to be consistant with other python code, but to be honest it is frustrating enough that I will probably change back to spaces". It's not clear which one you're using and which one you want might revert to. Probably a typo.
– Bruno
Oct 26 '12 at 12:54





I guess I'll have a disagree with your point of view then :-) I do prefer tabs in principle, but in practice, spaces are better when you don't have control of the viewer, such as web-based viewers (GitHub, Trac browser, ...), whereas you more or less always have control over the editor (with which you write). In addition, however arbitrary the choice is, a choice needs to be made, and it's been made by PEP-8 (otherwise you can end up with mixed types depending on the collaborative environment).
– Bruno
Oct 26 '12 at 16:23






Yeah there are very few places where you don't have control. And besides it will look fine if you get it wrong anyway. I'd say 95% of tab users use four spaces (including github), and the rest use 2, so in practice it is not remotely a problem. The mixed styles is of more concern, but as long as you are consistant within a project it really doesn't matter.
– Timmmm
Oct 26 '12 at 23:28





Sounds like a bug in emacs rather than a reason to use spaces...
– Timmmm
Nov 5 '13 at 10:07





"Different programmers can use different tab display sizes as they wish." Code is usually wrapped at a particular column, and changing the tab size breaks that. And then there are tools that don't have the option to change the tab width—have you ever tried running git diff on a file that's intended for a tabstop size of 4 or even 2? It will look awful.
– nyuszika7h
Nov 1 '14 at 10:54


git diff



I recently came across an article titled Python: Myths about Indentation which discusses this and related questions. The article has good reasons for recommending the use of spaces when writing Python code, but there is certainly room for disagreement.



I believe it's true that most Python programmers use spaces only.



Use an editor that allows you to insert spaces up to the tabstop when you press the TAB key, instead of inserting a t character. And then forget about it.



You CAN mix tabs and spaces... BUT a tab is considered to be the same indentation as 8 spaces, so unless your editor is set up to consider a tab to be 8 spaces you're asking for trouble when mixing them.





Python 3 won't let you mixing.
– hurturk
Nov 2 '13 at 11:37





And technically in Python 2 it isn't "considered to be the same indentation as 8 spaces" but instead considered as enough spaces to move to the next tabstop (defined as a multiple of 8 spaces).
– holdenweb
Apr 2 at 19:57





See also Python's interpretation of tabs and spaces to indent.
– Peter Mortensen
Jul 3 at 3:24



The only inconvenience I experience with using spaces instead of tabs is that you cannot easily remove an indentation level; you have to remove four spaces instead of just one tab.





Many editors have an "unindent" keystroke, such as Shift-Tab or Ctrl-[. Some editors even go so far as to erase 4 spaces when you hit Backspace at the right part of the line.
– RJHunter
Sep 8 '09 at 7:32





The problem is that it's 'some' editors. Most editors wont.
– Ikke
Sep 8 '09 at 8:43





Most editors that are designed for programming will. If your editor lacks this feature, it's probably missing a lot of other useful functionality.
– Steve S
Mar 5 '10 at 19:13





Ikke - what are you using? Vim/GVim certainly do. So does emacs. I believe TextPad and Notepad++ do as well. If your hammer is broken don't blame the nail.
– bobpaul
Oct 14 '10 at 17:43





And if the editor can't do smart indenting and unindenting, it's probably even less likely to be able to safely handle tabs, especially if a source file mixes tabs and spaces.
– Mr Fooz
Jun 14 '11 at 1:27



Tabs rule. Same argument for nested loops and you want to bring the outer loop "back" 1 level. Tip: If you want to convert old space-riddled python code into tabs use the TabOut utility available as an executable on http://www.textpad.com/add-ons/.





Tabs don't rule because: in some situations, you need to precisely indent some code to one-space-accuracy. in that case, either using only tabs would not allow you to achieve that, or using tabs and spaces would violate the hard rule of not mixing the two.
– Erik Allik
Mar 2 '12 at 14:16






Erik: There are no situations where you need to precisely align code (and PEP-8 recommends against it anyway). So it's really a trade-off between the ease-of-use and time-saving of tabs vs the perfect alignment abilities of spaces.
– Timmmm
Oct 22 '12 at 12:42





Douglas Crockford disagrees (08 min 49 secs).
– Peter Mortensen
Jul 3 at 3:37



I feel very strongly that whatever the historical convention, tabs are simply a better choice and should replace spaces in every future line of Python code written. Like kicking out an incompetent tyrant. My rationale for this is: simplicty as a core value. Use two or maybe four characters for the semantic task of one? There's no justification beyond tradition, IMO.





Douglas Crockford disagrees (08 min 49 secs).
– Peter Mortensen
Jul 3 at 3:48



When I was first learning Python, I was put off a little by the idea of significant white space, as most languages to use it are inflexible. That said, I was impressed by Python's ability to understand a variety of indentation styles. When considering what style to use for a new project, I think it is important to keep two things in mind.



Basically, there is a variable (which can be changed by including a comment at the top of a source file # tab-width: ) that defines the tab width. When Python encounters a tab, it increases the indentation distance to the next multiple of tab-width. Thus if a space followed by a tab is entered along the left of the file, the next multiple of tab-width is 8. If a tab by itself is entered, the same thing happens.



In this way, it is safe, if your editor is configured properly, to use tabs, and even to mix tabs and spaces. As long as you set your editor's tab stops to the same width as the Python tab-width declaration (or 8 if it is absent). It is generally a bad idea to use an editor with a tab width of other than 8 spaces, unless you specify the tab-width in the file.



I have encountered projects that use a mix of tabs and spaces successfully. Basically spaces are used to indent small sections, where the fact that it is in an indented section is relatively unimportant; while tabs are used to draw the reader's attention to a large structural feature. For example, classes begin with a tab, which simple conditional checks inside a function use two spaces.



Tabs are also useful when dealing with large blocks of text indented multiple levels. When you drop out of 3-4 levels of indentation, it is far easier to line up with the proper tab than it is to line up with the proper number of spaces. If a project doesn't use the PEP 8 recommended style, it is probably best to write a style guide into a file somewhere so that the indentation pattern remains consistent and other people can read explicitly how to configure their editor to match.



Also, Python 2.x has an option -t to issue warnings about mixed tabs and spaces and -tt to issue an error. This only applied to mixed tabs and spaces inside the same scope. Python 3 assumes -tt and so far as I've found, there is no way to disable that check.


-t


-tt


-tt



Experience and PEP-8 both clearly conclude that mixing spaces and TABs is to be avoided.
If you want to mix them you have to visualize whitespace in the IDE - but then you loose the advantage of Python's indentation making scopes easily visible. Visualizing whitespace in an IDE clutters the display.


TAB



If it's either TABs or spaces, then it must be spaces for a simple reason: One can switch almost all IDEs and text editors to automatically replace tabs with spaces, but the opposite is not true.



Even though there are IDEs that can automatically convert leading spaces in a line to tabs, this will eventually lead to having a mixture of tabs and spaces. Consider multi line statements such as function calls with lots of parameters or doc strings. While "ascii-art" is also to be avoided it may easily happen by accident that a single space is left over after the leading tabs.



Other answers brought several arguments in favor of tabs:


TAB


TAB


TAB



Imho, the main point that most (if not all) answers are missing here is the interaction between teams or individuals, especially in scenarios where the list of participants is not know at the start. When code meets code either all have to use tabs or all have to use spaces. It cannot be mixed without eventually running into functionality problems. People are not perfect. Tools are not perfect. That's why imho we should not use TABs at all.


TAB



No answer is complete without the link that Greg provided in his answer already: Python: Myths about Indentation



I'm primarily a C++ programmer, but sometimes my projects include small amounts of Python. I use tabs to indent my C++ code. This means that I have three options here:



For my projects, I generally go with option 3.



Editor-to-editor mistake occurs when you have mixed indentation within a file. This arises as follows: a block of code is indented with 4 spaces, and then one indentation level "in", it is indented with tabs. Now the heathen who did this (mixing tabs and spaces) had it so his tabs are also 4 spaces, so he sees no problems, and Python sees no problems.



Now our victim comes along later, and he has his tabs set to 8 spaces. Now our victims thinks the code looks all whacked, and fixes it by removing one level of indentation, which now makes the code look like it is still 2 levels of indentation, but is really one level. At this point all hell breaks loose.



The lesson here is that you should never, ever, mix tabs and spaces. If you keep to this, then it is easy to reindent your code into spaces or tabs, regardless of which you personally use. The best way to ensure you don't mix tabs and spaces is to always run python with -tt, which will produce an error when tabs and spaces are mixed.


python


-tt



As for tabs and spaces, I personally use tabs so separate indentation from appearance - it is much easier to change the appearance of code when it is indented with tabs than it is with spaces. I know this runs contrary to what 99% of Python programmers do, but that is my personal preference, and it is easy in any case to convert a tabbed file to a spaced one. The reverse is not always true, since you can accidentally whack out 4 spaces in strings, etc.





So, unless mixing tabs and spaces (which I agree is bad) then there is no other reason than convention?
– Hannes Ovrén
Sep 23 '08 at 7:58





Convention covers also the possibility of code exchange.
– tzot
Sep 23 '08 at 8:05



There's a scenario in which tabs simply don't work, namely: depending on the coding style you are using, you might need to indent some lines of code to one-space accuracy, i.e:


def foobar():
x = some_call(arg1,
arg2)



In that case, using purely tabs will not work at all; using tabs for main indent and spaces for sub-indent will work but will violate the hard rule of not mixing the two.



This will not be the case however when using a coding style/conventions document that avoids situations like in the above code example.





I would mix tabs and spaces like this: pastebin.com/5Cxer7E1. Mixing tabs and spaces is mostly a problem when spaces come before tabs in a given line or tabs and spaces are used inconsistently across lines. In the linked example, tabs provide initial indentation, while spaces provide alignment.
– Max Nanasy
Aug 9 '12 at 4:24






it's definitely possible but I think it would be hard to convince most developers that mixing spaces and tabs is fine after all.
– Erik Allik
Aug 12 '12 at 11:32





Don't wrap arguments like that, Python isn't Objective-C. (Yes, I know PEP-8 suggests it, but PEP-8 isn't perfect.) Avoid the issue by moving all arguments down (none on the first line) indented twice (to differentiate from code blocks which indent once).
– amcgregor
Jan 10 '13 at 20:39






I agree but that's beyond the point of not mixing.
– Erik Allik
Jan 30 '13 at 12:40





yuck, don't do this :) don't use spaces o/ avoid ASCII-Art !
– yota
Apr 12 '13 at 14:18



Everyone has different preferences on how much code should be indented. Let's say you share code with someone and he or she has different preferences regarding indentation. If the indentations are in tabs, your friend can always just change the tab width in their editor settings. However, if the indentations are in spaces, your friend will actually have to change the source code if he or she want to set it to their preference. Then when you get your friend's changes, you may decide to change it back to your preference. In this case, you will either have to deal with the tedium of changing indentation levels back and forth, or one person must adopt the other's preferences in indentation level. If both you and your friend use tabs, the fact that you have different preferences is a non-issue, as you can each see different indentation levels while the code remains unchanged. That is why, in my opinion, tabs are better than spaces for indentation in all programming languages.





Still, as you can see, the Python guidelines state that spaces are to be used, and not tabs.
– Hannes Ovrén
Jun 13 '11 at 12:38





Do they provide any reason for that recommendation? Most of these "coding style" preferences are completely arbitrary and are meant simply to ensure consistency in projects with multiple developers. However, if we all used tabs, there would be no need to mandate that indents be a specific number of spaces. Everybody could just set the tabs to look like however many spaces you want.
– Zhehao Mao
Jun 13 '11 at 15:32





@kigurai No, PEP-8 suggests that spaces should be used over tabs, it only states that tabs and spaces shouldn't be mixed. PEP-8 is also not "the Python guidelines" it is the style guide for the Python standard library and not a general style guide that should be followed by everyone like people seem to think.
– kyrias
Mar 27 '13 at 16:08






@Demizey, Well, true and false. It is true that PEP-8 does not say that you must use spaces, and not tabs. But it also clearly states "For new projects, spaces-only are strongly recommended over tabs." which is arguably the same thing as "use spaces". :)
– Hannes Ovrén
Mar 29 '13 at 13:07





@kigurai It is also true that it's the Python standard librarys style guide and is not meant to be followed by other projects.
– kyrias
Mar 31 '13 at 15:27



In addition to all the arguments already listed, I find this one fairly important (from Myths about indentation):



Also, tabs often get destroyed or wrongly converted during copy&paste operations, or when a piece of source code is inserted into a web page or other kind of markup code.



Another argument (strongly environment-specific, though) against tabs is that they are sometimes missing on phone keyboards. This could probably be remedied by installing an alternative keyboard, where possible.



An argument for tabs which no one seemed to have mentioned yet is that 1 tab is 1 character (0x09, 1 byte in the file), while 4 spaces are 4 characters (4 times 0x20, 4 bytes in the file); thus, using spaces results in a 4x waste of space.



To conclude this incoherent list of arguments, I would like to cite Tim Peters answer in the Issue 7012: Tabs is better than spaces for indentation:



The Python "spaces only" standard is for
distributed code. Years of early experience taught us beyond doubt that
tabs caused endless problems for shared code (...)





The size of tab characters is a weak argument. Computers are fast enough and disks are big enough. One of the strongest arguments for tabs is that each developer can pick the indent that they prefer.
– Kevin Cox
Mar 19 '14 at 13:16





I've never seen a website/program "destroy" tabs, if it does, it isn't made to handle code. If you post code on a website, it typically converts newlines, and displays as preformatted text anyway. Tabs are best way to indent code outside of a specialized character.
– bryc
Jul 21 '15 at 20:31



This is PEP 8 as of July 2017:



Enter image description here



It seems this statement doesn't leave room for any other choice.



But this isn't solely what PEP 8 tells us, few lines later:



Enter image description here



In the above, the first statement expresses a preference for spaces, and the second statement acknowledges the existence of code indented with tabs and this preference for some coders.



So: PEP 8 is tab indentation tolerant.
It doesn't tolerate tab and space mixed for indentation though, which, since indentation itself is mandatory, is understandable.



It may be worth mentioning that Google's Python coding style also follows the 4-space rule.



There are other various arguments and justifications in favor of either tabs or 4-space.



If you work in a company which enforce PEP 8, or regularly share your code with others who follow PEP 8, then common sense dictates 4-space. I am (was, maybe) used to tabs from C/C++. But with a properly set IDE, the difference becomes minimal.



How does that make a difference?



Some editors are configured by default to replace a single tab character with a set number of space characters, but some are not. If everyone uses spaces, this difference in default editor settings can be ignored.



Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?



Yes, there are other valid reasons as pointed out by many answers before me. "PEP-8" says so, however, is NOT one of those reasons. This comes from the self perpetuating myth that PEP-8 is the coding standard for all Python code, when in fact it's just the coding standard for the standard set of Python libraries. Some claim that PEP-8 is widely accepted, and some claim that most Python programmers use spaces instead of tabs. I would like to ask for proofs of these claims, as the number of votes on this site CLEARLY shows that tabs are preferred by the masses. I find it quite unfortunate that you have accepted "PEP8 says so" as the answer to your question, when in fact there are many other answers that actually explains the relative advantages and disadvantages of spaces and tabs.



Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?



It depends, and the answer to this final question is where I thought I could actually add some value to this thread. IMHO, regardless of the language being used, the best coding standard to use depends on the situation that you are in:



So which situation do you fall under?



Finally to make my stance clear, for my own solo projects, I use tabs because tabs make more sense to me, and I am more productive with tabs.



The problem with using spaces instead of tabs is the file-size becomes so incredibly large... For example, a 500 kB space-indented file could be reduced to 200 kB when swapping spaces for tabs which is why I always use tabs.



Smaller file-size means faster loading, compiling, execution (in some cases), etc..



To me, there is no point to using spaces, but if someone uses an editor which has issues with tabs, then they can replace "t" with " " or " " or whatever..



Use spaces in place of tabs, for the sole reason that you will make more money :)



Ref.: Developers Who Use Spaces Make More Money Than Those Who Use Tabs (Stack Overflow blog post).





You assume a causality, while this is probably only a correlation. Developers who use spaces may have another mindset that makes them more productive in some way, earning them more money, and that makes them prefer spaces. So if you use tabs and consider this option, know that your salary probably won't go up. On the other hand, if someone asks this question in an interview, don't hesitate to say that you use spaces if you think that will make you more eligible for the job. This means that you have to use them when you get the job btw. ;-)
– SPRBRN
Feb 27 at 20:18






Downvoters have a serious hate problem, how can you disagree with a joke? :D
– Antonio
Mar 15 at 20:07



I'm just starting out but I find it much easier to use tabs than spaces, and do not understand the PEP-8 advocation of spaces only. Sublime Text 2 does a great job of visualizing tabs with the off-white vertical, dotted line and while there are cases of me mixing a space or two to line up elements of a list or dictionary, I have not experienced a situation where that would be detrimental thing.



I love tabs but it is somehow incompatible with another rule I like: the 80 column limit.



If one chooses 4 spaces tabs and inserts 10 tabs, then there is space left for 40 characters to fulfill the 80 column limit.
If another coder prefers 8 spaces tabs, the same line will appear as 120 characters long and will not appear as a valid 80 columns line!



If you want to define a 80 column limit, then you have to choose a length for a tab. In this case having x spaces or a tab of length x does not really make a difference.



Edit: related thread: Maintaining Maximum Line Length When Using Tabs Instead of Spaces?



I believe there is a solution to have both:



In Notepad++, go to "preferences"--> "tab settings" and choose "Python" from the list on the right. Then make sure "tab size: 4", and check the box "replace [tab] by space". In this case, you can simply use the tab key to indent, but Notepad++ actually transform that to 4 spaces for you.





Yeah now what happens when you press delete? Or click in the middle of an ident. Or navigate left and right through the indent using arrow keys?
– Timmmm
Feb 9 '16 at 9:50





You are right. It could be an issue there.
– Saeed
Feb 22 '16 at 14:37



I think one of the main benefits to using spaces is that you remove variability in how your source code is rendered across the plethora of external tools which have to interact with the source beyond one's choice editor and whatever settings they've configured it in.



As some concrete examples consider the rendering of Python docstrings in a tooltip in Visual Studio Code, or in a diff tool like Beyond Compare or WinMerge, performance or code coverage tools, etc. Basically all these various other interfacing tooling can each have different settings for how tabs are interpreted and it can be annoying and at times disorienting to find things vastly different or pushed way off screen among the toolsets you may dive in and out of.



In a nutshell you define alignment in the source rather than wrangling down a uniform configuration for the suite of tools in your arsenal. Spaces are strictly interpreted in a monospace font to give reliable and consistent alignment across the full span of tooling due to the font's definition, not a third party's tab rendering implementation/configuration.



Another angle to this is in copying leading tabs source to run at a terminal where the tab character can trigger an inadvertent tab completion. For example, if you copy the following Python source (tabs used as indentation),


cmd_create_db = '''CREATE TABLE test (
Col1 INTEGER,
Col2 INTEGER,
Col3 TEXT)'''



you may see something like follows (seen at Visual Studio Code's integrated terminal)...


>>> cmd_create_db = '''CREATE TABLE test (
... .DS_StoreCol1 INTEGER,
... .DS_StoreCol2 INTEGER,
... .DS_StoreCol3 TEXT)'''
>>> cmd_create_db
'CREATE TABLE test (n.DS_StoreCol1 INTEGER,n.DS_StoreCol2 INTEGER,n.DS_StoreCol3 TEXT)'



(Aside: I had wondered if this observation of consistency across tooling is a mark of a discriminating mind of a sharp developer looking to order the world that may indicate a hint at the salary difference found on Stack Overflow.)



I use two space indentation and an editor (kwrite) that inserts spaces instead of tabs when I hit the tab key.



Having recently had to deal with existing code that was mixing spaces and tabs, it's really confusing.



When you're mixing (which you really shouldn't do, but which does exist out there unfortunately), it appears that "1 tab == 1 indent level" isn't true.



Take the following example (tried with Python 2.7):


# Mostly use spaces
class TestClass:
def __init__(self):
self.total = 0

def add(self, x):
# 8 spaces at the start of the following line:
self.total += x
# SO automatically uses spaces, but use tabs in the next 2 lines.
# One tab at the start of the following line:
if self.total > 10:
# Two tabs at the start of the following line:
print "Greater than 10!"
# Now use spaces again.

return self.total

tc = TestClass()

print "Total: %d" % (tc.add(5),)
print "Total: %d" % (tc.add(5),)
print "Total: %d" % (tc.add(5),)



Here, there are 4 spaces before def add(...) (1 identation level), 8 spaces before self.total += x (2 indentation levels), and a single tab before if self.total > 10.


def add(...)


self.total += x


if self.total > 10



Yet, that single tab behaves like 2 indentation levels, since this code works. In contrast, if you replace all tabs with 4 spaces (a single indentation level, that's where the def within the class are), you'll get an unexpected indent error before return, because it's no longer in a def block.


def


return


def



This is really confusing with editors that show tabs as 4 characters. Of course, this can be configured, but this also affect source code viewers (e.g. the likes of GitHub) where it's not necessarily easy to configure (or immediately visible that you need to do so, when you can).



The tab v.s. space behaviour will always depend on the editor:



Both have their downsides. The bottom line is that there needs to be an arbitrary choice between tabs and spaces, but they should never be mixed. Since you never know how your code is going to be read and used later, it's good to have a convention that affects all python coders. PEP-8 says spaces, so be it.



What matters is not to do it the Java way:



Four spaces should be used as the unit of indentation. The exact
construction of the indentation (spaces vs. tabs) is unspecified. Tabs
must be set exactly every 8 spaces (not 4).



Yes... 1 tab = 2 indentation levels in the Java world! Thankfully, it doesn't have the same significance in terms of compilation.




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).


Would you like to answer one of these unanswered questions instead?

Popular posts from this blog

PHP contact form sending but not receiving emails

PHP parse/syntax errors; and how to solve them?

Laravel 5.6 - Permission denied when trying to retrieve image