Set up EditorConfig for Your Django Project

Let us configure our writing implements to all be the same.

This post is an adapted extract from my book Boost Your Django DX, available now.

The “tabs versus spaces” war is scheduled to rage on until the heat death of the universe. And whilst the Python ecosystem is firmly in the “spaces” camp, there remain numerous other text formatting options.

Inconsistent text formatting between team members can lead to unnecessary editing and even bugs. So it’s best to normalize text formatting in your projects.

EditorConfig is a standard for text editor configuration. It’s built-in to many text editors, such as PyCharm and GitHub’s web editor. For other text editors, you need to install a small plugin, available for nearly every text editor under the sun.

To set up EditorConfig for your project, create a file called .editorconfig the root of your repository. Note the . prefix, which makes the file hidden on Unix systems. The .editorconfig file uses INI file syntax, as parsed by Python’s configparser module.

Here is a .editorconfig file suitable for most Django projects:

# http://editorconfig.org

root = true

[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true

[*.py]
indent_size = 4

Here’s what this configuration does:

Fantastic.

For many projects you should be able to use this .editorconfig file as-is. Unfortunately there’s no easy way to reformat your existing files to match all the rules. But pre-commit has two small tools that can help with particular rules (trailing-whitespace and end-of-file-fixer) [these are described later in the book].

You can customize other file types, or even specific filenames, by adding further sections. For example, to ensure your Makefiles use tabs for indentation:

[Makefile]
indent_style = tab

Cowabunga, your team’s text editors are all in sync!


Learn how to make your tests run quickly in my book Speed Up Your Django Tests.


Subscribe via RSS, Twitter, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: