IndentingPython

The official Style Guide for Python Code states that spaces, with 4 spaces per level, are the preferred indentation method and that tabs should be used solely to remain consistent with code that is already indented with tabs. Mixed use of tabs and spaces for indentation is strongly discouraged for Python 2 and an error in Python 3.

The major modes described at PythonMode will normally handle this: they will guess the per-level indentation used in Python source (but may be used to override an incorrect guess) and they will also set ‘indent-tabs-mode’ to ‘nil’.

For code that already uses tabs for indentation indent-tabs-mode should be set to ‘t’ rather than the default of ‘nil’. GuessStyle can do this automatically. Enable it like so:

   (add-hook 'python-mode-hook 'guess-style-guess-tabs-mode)
   (add-hook 'python-mode-hook (lambda ()
                                    (guess-style-guess-tab-width)))

For such code SmartTabs#Python will use tabs only for expressing the indentation level, so that lining up of code is independent of the tab size.

PyIndent allows using C-like braces embedded in comments to manage indentation.

when using python-mode.el and you want TAB characters, and not spaces this is what worked for me:

    (add-hook 'python-mode-hook
	    (lambda ()
		    (setq-default indent-tabs-mode t)
		    (setq-default tab-width 4)
		    (setq-default py-indent-tabs-mode t)
	    (add-to-list 'write-file-functions 'delete-trailing-whitespace)))

OK the delete-trailing-whitespace is extra magic and unrelated.


CategoryIndentation