Related
This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed last month.
I'm trying to create an application in Python 3.2 and I use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out "inconsistent use of tabs and spaces in indentation" when I try to run the program.
How can I change the spaces into tabs? It's driving me crazy.
import random
attraktioner = ["frittfall","bergodalbana","spökhuset"]
class Nojesfalt:
def __init__(self, attraktion):
self.val = attraktion
self.langd = 0
self.alder = 0
#längdgräns för fritt fall
def langdgrans(self):
print("")
self.langd = int(input("Hur lång är du i cm? "))
if self.langd < 140:
print("tyvärr, du är för kort, prova något annat")
return 0
elif self.langd >= 140:
print("håll dig hatten, nu åker vi!")
print(" ")
return 1
#åldersgräns för spökhuset
def aldersgrans(self):
print("")
self.alder = int(input("Hur gammal är du? "))
if self.alder < 10:
print("tyvärr, du är för ung, prova något annat")
return 0
elif self.alder >= 10:
print("Gå in om du törs!")
print(" ")
return 1
#åker attraktion frittfall lr bergodalbana
def aka(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("åkturen gick åt skogen, bättre lycka nästa gång")
elif tal >= 20:
print("jabbadabbbadoooooooo")
return 1
#går i spökhuset
def aka1(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("du är omringad av spöken och kan inte fortsätta") return 0
elif tal >= 20:
print("Buhuuuuuu, buuuhuuuu")
return 1
#programkod
print("Välkommen till nöjesfältet, vad vill du göra?")
print(" ")
while 1:
vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")
if vald_attr == "1":
val = Nojesfalt(attraktioner[0])
if val.langdgrans() == 1:
val.aka()
elif vald_attr == "2":
val = Nojesfalt(attraktioner[1])
val.aka()
elif vald_attr == "3":
val = Nojesfalt(attraktioner[2])
if val.aldersgrans() == 1:
val.aka1()
elif vald_attr == "4":
break
Don't use tabs.
Set your editor to use 4 spaces for indentation.
Make a search and replace to replace all tabs with 4 spaces.
Make sure your editor is set to display tabs as 8 spaces.
Note: The reason for 8 spaces for tabs is so that you immediately notice when tabs have been inserted unintentionally - such as when copying and pasting from example code that uses tabs instead of spaces.
For VSCode users
Ctrl+Shift+P or View->Command Palette.
Type
>Convert Indentation to Spaces
press Enter.
Using the autopep8 command below fixed it for me:
autopep8 -i my_file.py
Documentation for autopep8 linked here.
With the IDLE editor you can use this:
Menu Edit → Select All
Menu Format → Untabify Region
Assuming your editor has replaced 8 spaces with a tab, enter 8 into the input box.
Hit select, and it fixes the entire document.
When using the sublime text editor, I was able to select the segment of my code that was giving me the inconsistent use of tabs and spaces in indentation error and select:
view > indentation > convert indentation to spaces
which resolved the issue for me.
It is possible to solve this problem using notepad++ by replacing Tabs with 4 Spaces:
Choose Search -> Find... or press Ctrl + F
Select the Replace tab
In the box named Search Mode choose Extended(\n, \r, \t, \0, \x...)
In the field Find what : write \t
In the field Replace with : press Space 4 times. Be sure that there is nothing else in this field.
Click on the button Replace All
Generally, people prefer indenting with space. It's more consistent across editors, resulting in fewer mismatches of this sort. However, you are allowed to indent with tab. It's your choice; however, you should be aware that the standard of 8 spaces per tab is a bit wide.
Concerning your issue, most probably, your editor messed up. To convert tab to space is really editor-dependent.
On Emacs, for example, you can call the method 'untabify'.
On command line, you can use a sed line (adapt the number of spaces to whatever pleases you):
sed -e 's;\t; ;' < yourFile.py > yourNedFile.py
If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces → choose Anaconda → click on autoformat. Done. Or press Ctrl + Alt + R.
Sublime Text 3
In Sublime Text, WHILE editing a Python file:
Sublime Text menu > Preferences > Settings - Syntax Specific :
Python.sublime-settings
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
I recently had the same problem and found out that I just needed to convert the .py file's charset to UTF-8 as that's the set Python 3 uses.
BTW, I used 4-space tabs all the time, so the problem wasn't caused by them.
What I did when the same error popped up: Select everything (Str + A) and press Shift + Tab. So nothing was indented anymore. Now go back to the lines you want to have indented, and put it back how you want it.
It worked for me...
If you use ATOM:
Go to Menu: Packages --> WhiteSpace --> Convert all Tabs to Spaces
Try deleting the indents and then systematically either pressing tab or pressing space 4 times. This usually happens to me when I have an indent using the tab key and then use the space key in the next line.
Your problem is due to your editor limitations/configuration. Some editors provide you of tools to help with the problem by:
Converting tabs into spaces
For example, if you are using Stani's Python editor you can configure it to do it on saving.
Converting spaces into tabs
If you are using ActiveState Komodo you have a tool to 'tabify' your code. As others already pointed, this is not a good idea.
Eclipse's Pydev provides functions "Convert tabs to space-tabs" and "Convert space-tabs to tabs".
I use Notepad++ and got this error.
In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.
To solve the problem, I just deleted the tab before the line then added four spaces.
There was a duplicate of this question from here but I thought I would offer a view to do with modern editors and the vast array of features they offer. With python code, anything that needs to be intented in a .py file, needs to either all be intented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with atom, going to preferences and then editor you can see the following two options:
Then if your code is using spaces, you will see small dots where your code is indented:
And if it is indented using tabs, you will see something like this:
Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left, this is because of something called pep8 pep8 documentation, which is basically a uniform style guide for python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples code, it is in pep8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to pep8 warning code W191,
I hope all the above helps you understand the nature of the problem you are having and how to prevent it in the future.
SOULUTION FOR SUBLIME TEXT
My Solution to this problem was to open it in idle editor and then idle editor will uncover your problem
e.g
SUBLIME TEXT
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
IDLE EDITOR
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
I am not saying that you should only use idle editor. I'm saying that if you get that error you should check idle editor
I had the same error. I had to add several code lines to an existing *.py file. In Notepad++ it did not work.
After adding the code lines and saving, I got the same error. When I opened the same file in PyCharm and added the lines, the error disappeared.
I oddly ran into a similar issue with one of my .py files. I simply opened the file in Pycharm and pressed Option+Command+L which correctly formats the file contents in one go.
I suspect I was having trouble because I coded this particular .py file through jupyter labs as opposed to my usual choice of sublime text or Pycharm and therefore ran into some hidden indentation issues many answers here have alluded to
Use pylint it will give you a detailed report about how many spaces you need and where.
The following trick has worked for me:
Copy and paste the code in the notepad.
Then from the notepad again select all and copy the code
Paste in my views.py
Select all the newly pasted code in the views.py and remove all the tabs by pressing shift+tab from the keyboard
Now use the tab key again to use the proper indentation
For Anaconda, Spyder users you can go to Source> Fix indentation
If your editor doesn't recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.
Solving this using Vim editor
Open terminal (Ctrl + Alt + T).
Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
[Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
Go to the line where you have this problem (ESC :<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.
Well I had the same problem and I realised that the problem is that I copied code from another python editor to sublime.
I was working with jupyter notebook and then I copied the code into sublime. Apparently when you make specific modifications (like moving code in functions) then indentation gets messy and this is where the problem comes from.
So just stick to one editor. If you do so, then you will be having no problem.
For Jupyter users:
CTRL + Shift + P Automatically idents the selection:
While the original question is about self authored code, the search engines lead here for when searching for the title string. An error message one might very likely get when attempting to make use of an already existing library or tool.
For those finding their way here when attempting to use someone elses code; It is a python2 vs. python3 thing, according to Tab Error in Python (an answer which also refers to the relevant section of the PEP8 styleguide.
I got the same errors but could not figure out what I was doing wrong.
So I fixed it by running auto-indent on my code and allowing the machine to fix my fault.
If anyone is wondering how I did that.
Simple.
Go in vim.
Type in G=gg.
This will automatically fix everything. Good luck :)
Sometimes, tab does mess up while indenting. One way is to obviously use the tab and backspace to correctly indent the code.
Another way is to use space 4 times (depending on how much you want to indent).
A weird way that worked for me when nothing else worked, whichever line I getting the error, I backspaced that line to the previous line and then pressed enter. It automatically indented the line to correct position and I was not getting any error after that.
Hopefully, this should help.
This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed last month.
I'm trying to create an application in Python 3.2 and I use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out "inconsistent use of tabs and spaces in indentation" when I try to run the program.
How can I change the spaces into tabs? It's driving me crazy.
import random
attraktioner = ["frittfall","bergodalbana","spökhuset"]
class Nojesfalt:
def __init__(self, attraktion):
self.val = attraktion
self.langd = 0
self.alder = 0
#längdgräns för fritt fall
def langdgrans(self):
print("")
self.langd = int(input("Hur lång är du i cm? "))
if self.langd < 140:
print("tyvärr, du är för kort, prova något annat")
return 0
elif self.langd >= 140:
print("håll dig hatten, nu åker vi!")
print(" ")
return 1
#åldersgräns för spökhuset
def aldersgrans(self):
print("")
self.alder = int(input("Hur gammal är du? "))
if self.alder < 10:
print("tyvärr, du är för ung, prova något annat")
return 0
elif self.alder >= 10:
print("Gå in om du törs!")
print(" ")
return 1
#åker attraktion frittfall lr bergodalbana
def aka(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("åkturen gick åt skogen, bättre lycka nästa gång")
elif tal >= 20:
print("jabbadabbbadoooooooo")
return 1
#går i spökhuset
def aka1(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("du är omringad av spöken och kan inte fortsätta") return 0
elif tal >= 20:
print("Buhuuuuuu, buuuhuuuu")
return 1
#programkod
print("Välkommen till nöjesfältet, vad vill du göra?")
print(" ")
while 1:
vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")
if vald_attr == "1":
val = Nojesfalt(attraktioner[0])
if val.langdgrans() == 1:
val.aka()
elif vald_attr == "2":
val = Nojesfalt(attraktioner[1])
val.aka()
elif vald_attr == "3":
val = Nojesfalt(attraktioner[2])
if val.aldersgrans() == 1:
val.aka1()
elif vald_attr == "4":
break
Don't use tabs.
Set your editor to use 4 spaces for indentation.
Make a search and replace to replace all tabs with 4 spaces.
Make sure your editor is set to display tabs as 8 spaces.
Note: The reason for 8 spaces for tabs is so that you immediately notice when tabs have been inserted unintentionally - such as when copying and pasting from example code that uses tabs instead of spaces.
For VSCode users
Ctrl+Shift+P or View->Command Palette.
Type
>Convert Indentation to Spaces
press Enter.
Using the autopep8 command below fixed it for me:
autopep8 -i my_file.py
Documentation for autopep8 linked here.
With the IDLE editor you can use this:
Menu Edit → Select All
Menu Format → Untabify Region
Assuming your editor has replaced 8 spaces with a tab, enter 8 into the input box.
Hit select, and it fixes the entire document.
When using the sublime text editor, I was able to select the segment of my code that was giving me the inconsistent use of tabs and spaces in indentation error and select:
view > indentation > convert indentation to spaces
which resolved the issue for me.
It is possible to solve this problem using notepad++ by replacing Tabs with 4 Spaces:
Choose Search -> Find... or press Ctrl + F
Select the Replace tab
In the box named Search Mode choose Extended(\n, \r, \t, \0, \x...)
In the field Find what : write \t
In the field Replace with : press Space 4 times. Be sure that there is nothing else in this field.
Click on the button Replace All
Generally, people prefer indenting with space. It's more consistent across editors, resulting in fewer mismatches of this sort. However, you are allowed to indent with tab. It's your choice; however, you should be aware that the standard of 8 spaces per tab is a bit wide.
Concerning your issue, most probably, your editor messed up. To convert tab to space is really editor-dependent.
On Emacs, for example, you can call the method 'untabify'.
On command line, you can use a sed line (adapt the number of spaces to whatever pleases you):
sed -e 's;\t; ;' < yourFile.py > yourNedFile.py
If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces → choose Anaconda → click on autoformat. Done. Or press Ctrl + Alt + R.
Sublime Text 3
In Sublime Text, WHILE editing a Python file:
Sublime Text menu > Preferences > Settings - Syntax Specific :
Python.sublime-settings
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
I recently had the same problem and found out that I just needed to convert the .py file's charset to UTF-8 as that's the set Python 3 uses.
BTW, I used 4-space tabs all the time, so the problem wasn't caused by them.
What I did when the same error popped up: Select everything (Str + A) and press Shift + Tab. So nothing was indented anymore. Now go back to the lines you want to have indented, and put it back how you want it.
It worked for me...
If you use ATOM:
Go to Menu: Packages --> WhiteSpace --> Convert all Tabs to Spaces
Try deleting the indents and then systematically either pressing tab or pressing space 4 times. This usually happens to me when I have an indent using the tab key and then use the space key in the next line.
Your problem is due to your editor limitations/configuration. Some editors provide you of tools to help with the problem by:
Converting tabs into spaces
For example, if you are using Stani's Python editor you can configure it to do it on saving.
Converting spaces into tabs
If you are using ActiveState Komodo you have a tool to 'tabify' your code. As others already pointed, this is not a good idea.
Eclipse's Pydev provides functions "Convert tabs to space-tabs" and "Convert space-tabs to tabs".
I use Notepad++ and got this error.
In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.
To solve the problem, I just deleted the tab before the line then added four spaces.
There was a duplicate of this question from here but I thought I would offer a view to do with modern editors and the vast array of features they offer. With python code, anything that needs to be intented in a .py file, needs to either all be intented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with atom, going to preferences and then editor you can see the following two options:
Then if your code is using spaces, you will see small dots where your code is indented:
And if it is indented using tabs, you will see something like this:
Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left, this is because of something called pep8 pep8 documentation, which is basically a uniform style guide for python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples code, it is in pep8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to pep8 warning code W191,
I hope all the above helps you understand the nature of the problem you are having and how to prevent it in the future.
SOULUTION FOR SUBLIME TEXT
My Solution to this problem was to open it in idle editor and then idle editor will uncover your problem
e.g
SUBLIME TEXT
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
IDLE EDITOR
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
I am not saying that you should only use idle editor. I'm saying that if you get that error you should check idle editor
I had the same error. I had to add several code lines to an existing *.py file. In Notepad++ it did not work.
After adding the code lines and saving, I got the same error. When I opened the same file in PyCharm and added the lines, the error disappeared.
I oddly ran into a similar issue with one of my .py files. I simply opened the file in Pycharm and pressed Option+Command+L which correctly formats the file contents in one go.
I suspect I was having trouble because I coded this particular .py file through jupyter labs as opposed to my usual choice of sublime text or Pycharm and therefore ran into some hidden indentation issues many answers here have alluded to
Use pylint it will give you a detailed report about how many spaces you need and where.
The following trick has worked for me:
Copy and paste the code in the notepad.
Then from the notepad again select all and copy the code
Paste in my views.py
Select all the newly pasted code in the views.py and remove all the tabs by pressing shift+tab from the keyboard
Now use the tab key again to use the proper indentation
For Anaconda, Spyder users you can go to Source> Fix indentation
If your editor doesn't recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.
Solving this using Vim editor
Open terminal (Ctrl + Alt + T).
Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
[Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
Go to the line where you have this problem (ESC :<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.
Well I had the same problem and I realised that the problem is that I copied code from another python editor to sublime.
I was working with jupyter notebook and then I copied the code into sublime. Apparently when you make specific modifications (like moving code in functions) then indentation gets messy and this is where the problem comes from.
So just stick to one editor. If you do so, then you will be having no problem.
For Jupyter users:
CTRL + Shift + P Automatically idents the selection:
While the original question is about self authored code, the search engines lead here for when searching for the title string. An error message one might very likely get when attempting to make use of an already existing library or tool.
For those finding their way here when attempting to use someone elses code; It is a python2 vs. python3 thing, according to Tab Error in Python (an answer which also refers to the relevant section of the PEP8 styleguide.
I got the same errors but could not figure out what I was doing wrong.
So I fixed it by running auto-indent on my code and allowing the machine to fix my fault.
If anyone is wondering how I did that.
Simple.
Go in vim.
Type in G=gg.
This will automatically fix everything. Good luck :)
Sometimes, tab does mess up while indenting. One way is to obviously use the tab and backspace to correctly indent the code.
Another way is to use space 4 times (depending on how much you want to indent).
A weird way that worked for me when nothing else worked, whichever line I getting the error, I backspaced that line to the previous line and then pressed enter. It automatically indented the line to correct position and I was not getting any error after that.
Hopefully, this should help.
Whenever I append a : character in Vim in Python mode, it either:
indents the line
dedents the line
does nothing
What is it even trying to do, and how do I get rid of this behavior?
Certain keys, when pressed, will trigger Vim's indent feature, which will attempt to set the correct amount of indentation on the current line. (You can manually trigger this by typing == in normal mode.)
You can change which keys trigger this behavior, but first you need to know what indenting mode is being used.
First, execute :set indentexpr?. If it is nonempty (I would expect this for Python), then indentexpr mode is being used. In this case, executing :set indentkeys? gives you the list of trigger keys. To remove the colon, execute :setlocal indentkeys-=:.
If indentexpr is empty, then you are probably using cindent mode, and :set cindent? will tell you that cindent is set. In this case, do the same as before, but using cinkeys instead of indentkeys. (Note that indentexpr mode takes precedence over cindent mode.)
Nathan Grigg's answer set me on the right track. I had to make a few changes for my setup.
I had to use :setlocal indentkeys-=<:>, because in my case :set indentkeys? showed indentkeys=0{,0},!^F,o,O,e,<:>,=elif,=except.
Also, putting :setlocal indentkeys-=<:> in .vim/after/ftplugin/python.vim did not work to make the change permanent. I found that there is a built-in vim python indent file that runs AFTER this after-ftplugin file.
To diagnose, open a Python file for editing, and run :scriptnames. That will show you a list of all the vim scripts that have run, in order of precedence. The scripts at the bottom of that list have been applied most recently, and take precedence. See this question on SuperUser for more info.
When I did that, it showed me a built-in vim file at /my-install-path/vim/7.4.1830/share/vim/vim74/indent/python.vim. Sure enough, that was setting <:> as part of the indent keys.
To fix it, I set an autocommand in .vimrc, and that really gets the last word.
autocmd FileType python setlocal indentkeys-=<:>
Update
I had to add :setlocal indentkeys-=: after all. Here's what I have in my .vimrc now.
autocmd FileType python setlocal indentkeys-=<:>
autocmd FileType python setlocal indentkeys-=:
It is trying to be helpful. If you want to turn off all the auto-indenting for the current file,
:setlocal noautoindent
:setlocal nocindent
:setlocal nosmartindent
:setlocal indentexpr=
Or, you can add set in your vimrc file. You can do these per file type too. See here
TL;DR I disabled autoindentation by typing:
:set indentexpr=
then hitting the ENTER key.
It's a quick fix without needing to understand indentkeys ..
Thanks to Christian Long for the docs to indentkeys, where I noticed (my emphasis):
A list of keys that, when typed in Insert mode, cause reindenting of
the current line. Only happens if 'indentexpr' isn't empty.
Tip - you might want to save a copy of the existing value of indentexpr before you clear it out. To see that (and any other values that are set) just type:
:set
HTH
When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.
For example, when writing this in vim
for i in range(10):
#
the # does not stay there where I entered it.
It is moved like so, by vim.
for i in range(10):
#
Does anyone know of a configuration item in vim that would change this?
If it helps, I am using Ubuntu 8.10.
I found an answer here http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash
It seems that the vim smartindent option is the cause of the problem.
The referenced page above describes work-a-rounds but after reading the help in smartindent in vim itself (:help smartindent), I decided to try cindent instead of smartindent.
I replaced
set smartindent
with
set cindent
in my .vimrc file
and so far it is working perfectly.
This changed also fixed the behavior of '<<' and '>>' for indenting visual blocks that include python comments.
There are more configuration options for and information on indentation in the vim help for smartindent and cindent (:help smartindent and :help cindent).
#PolyThinker Though I see that response a lot to this question, in my opinion it's not a good solution. The editor still thinks it should be indented all the way to left - check this by pushing == on a line that starts with a hash, or pushing = while a block of code with comments in it is highlighted to reindent.
I would strongly recommend filetype indent on, and remove the set smartindent and set autoindent (or set cindent) lines from your vimrc. Someone else (appparently David Bustos) was kind enough to write a full indentation parser for us; it's located at $VIMDIRECTORY/indent/python.vim.
(Paul's cindent solution probably works for python, but filetype indent on is much more generally useful.)
I have the following lines in my .vimrc, seems to be installed by default with my Ubuntu 8.10
set smartindent
inoremap # X^H#
set autoindent
And I don't observe the problem. Maybe you can try this. (Note that ^H should be entered by Ctrl-V Ctrl-H)
My solution to the unindenting of #:
If you use cindent, recognize that it is designed for C and C++ coding. Here, a # means you are creating a #DEFINE or #MACRO(), so the behavior is correct. But for other languages where # is a comment, it is irritating.
The following worked for me:
" cindent enable specific indenting for C code
" set cin nocin
set cin
" cinkeys The default cinkeys causes leading # to unindent to column 0.
" To prevent this, remove the 0# from the definition.
" set cinkeys=0{,0},0),:,0#,!^F,o,O,e - default
set cinkeys=0{,0},0),:,!^F,o,O,e
It's caused by the 'smartindent' feature. If you have :set smartindent in your .vimrc you need to remove it.
Some of the other answers were useful, but none were enough to prevent Vim from reindenting a line when '#' is the first character. PolyThinker's answer didn't work for me, but it gave a clue that '#' could be remapped to "insert a character, then #, then delete the extra character and put the cursor where it should be". This is the mapping that does that:
inoremap # X#<left><backspace><right>
This is needed because vim's syntax packages seem to treat '#' as a special character, no matter how the options are set. I want a line started with '#' to be the same as a line begun with any other character. The most reliable solution I've found is the above mapping, which actually does change the line's first character.
Note: I've found this mapping causes problems after running I#<esc> then pressing "." to redo the previous insertion. I haven't found a solution yet.
My Vim configuration doesn't do that. You might try the python.vim script available from this link: http://www.vim.org/scripts/script.php?script_id=790
I removed set smartindent from ~/.vimrc but it still didn't disable smartindent. When I opened a .py file and ran :set smartindent? it displayed smartindent.
Turns out that further down in the ~/.vimrc was this line:
autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
^^^^^^^^^^^
Once I deleted "smartindent" from that line, then smartindent was finally disabled and my comments were indented properly again.
As I write code in Python and suddenly feel like adding a new block in front of the code I have already written... the indentation of the complete code is affected...
It is a very tedious process to move to each line and change the indentation...is there a way to do auto indent or something?
For example:
def somefunction:
x =5
return x
If I want to add a control block
For example:
def somefunction:
if True:
x =5
return x
return 0
this small change of adding a control block took a lot of tab work...
Is there a shortcut or something to do this easily?
I don't know what wacky planets everyone is coming from, but in most editors that don't date back to the stone age, indenting blocks of code typically only requires that a block of text be selected and Tab be pressed. On the flip side, Shift+Tab usually UNdents the block.
This is true for Visual Studio, Notepad2, e, Textmate, Slickedit, #Develop, etc. etc. etc.
If you're not doing large multi-file projects, I strongly recommend Notepad2. Its a very lightweight, free, easy-to-use notepad replacement with just enough code-centric features (line numbers, indentation guides, code highlighting, etc.)
In the Idle editor, you can just select the lines you want to indent and hit Tab.
I should note that this doesn't actually insert any tabs into your source, just spaces.
In IDLE I just use ctrl+] and ctrl+[ on a block of code.
With emacs there's Python mode. In that mode you highlight and do:
ctrl-c >
ctrl-c <
Use VI and never program the same again. :^)
[Funny ;-)] Dude, I told you that you would need one developer less if you had this new keyboard model
Pythonic keyboard http://img22.imageshack.us/img22/7318/pythonkeyboard.jpg
If you are using vim there is a plugin specifically for this: Python_fn.vim
It provides useful python functions (and menu equivalents):
]t -- Jump to beginning of block
]e -- Jump to end of block
]v -- Select (Visual Line Mode) block
]< -- Shift block to left
]> -- Shift block to right
]# -- Comment selection
]u -- Uncomment selection
]c -- Select current/previous class
]d -- Select current/previous function
]<up> -- Jump to previous line with the same/lower indentation
]<down> -- Jump to next line with the same/lower indentation
Vim: switch to visual mode, select the block, use > to indent (or < to unindent).
See also: Indent multiple lines quickly in vi
In TextMate, just highlight the lines you want to indent and use:
⌘ + [
or
⌘ + ]
To move the text in the appropriate direction.
PyDev, which you can find at http://pydev.sourceforge.net/ has a "Code Formatter". It also has autoindent feature. It is a plugin for Eclipse which is freely available for Mac too.
Another option would be http://code.google.com/p/macvim/ if you are familiar or invest time for Vim, which has lots of autoindent features not just for Python.
But, do not forget that, in Python, indentation changes the meaning of the program unlike C family languages. For example for C or C#, a utility program can beautify the code according to the "{" and "}" symbols. But, in Python that would be ambiguous since a program can not format the following:
#Say we wrote the following and expect it to be formatted.
a = 1
for i in range(5):
print i
a = a + i
print a
Do you expect it to be
a = 1
for i in range(5):
print i
a = a + i
print a #Will print 5
or
a = 1
for i in range(5):
print i
a = a + i
print a #Will print 11
which are two different snippets.
In Komodo the Tab and Shift Tab both work as expected to indent and unindent large blocks of code.
In vim, you can enter:
>>
to indent a line. If you enter:
5>>
you indent the 5 lines at and below the cursor. 5<< does the reverse.