Set python indent to 2 spaces in emacs 23?

dfrankow picture dfrankow · Nov 23, 2010 · Viewed 26.9k times · Source

I am using emacs 23.1.1 on Ubuntu 10.04. I wish to program in Python with a 2-space indent. emacs looks to have a default mode for python (python.el?).

I put the following in my .emacs:

    ;; Only spaces, no tabs
    (setq indent-tabs-mode nil)

    ;; Always end a file with a newline
    (setq require-final-newline nil)

    ;; Don't know which of these might work
    (setq-default tab-width 2)
    (setq-default python-indent 2)
    (setq-default py-indent-offset 2)

When I edit a Python file, it uses a 4-space indent. When I try C-h v python-indent it says:

    python-indent's value is 4
    Local in buffer webpage_cache.py; global value is 2

        This variable is safe as a file local variable if its value
        satisfies the predicate `integerp'.

    Documentation:
    Number of columns for a unit of indentation in Python mode.
    See also `M-x python-guess-indent'

    You can customize this variable.

That is, it is 4, not 2. Grr. I tried customizing the variable and saving, still 4. I tried customize-group indent, still 4.

How do I get emacs to pay attention?

Answer

Vulpecula picture Vulpecula · Dec 13, 2010

You can put this into your .emacs file:

(add-hook 'python-mode-hook '(lambda () 
 (setq python-indent 2)))

The reason why

    (setq-default python-indent 2)

does not work may because this variable does not exit when .emacs is loaded. (But I am an emacs newbie. I am not sure about my explanation.)

However, PEP 8 -- Style Guide for Python Code recommends "4 spaces per indentation level" and I find 4 spaces more readable. I actually use this piece of code to force a 4 spaces indentation.