One of Guido’s key insights is that code is read much more often than it
is written. The guidelines provided here are intended to improve the
readability of code and make it consistent across the wide spectrum of
Python code. As PEP 20 says, “Readability counts”.
A style guide is about consistency. Consistency with this style guide is
important. Consistency within a project is more important. Consistency
within one module or function is most important.
But most importantly: know when to be inconsistent — sometimes the style
guide just doesn’t apply. When in doubt, use your best judgment. Look
at other examples and decide what looks best. And don’t hesitate to ask!
Two good reasons to break a particular rule:
(1) When applying the rule would make the code less readable, even for
someone who is used to reading code that follows the rules.
(2) To be consistent with surrounding code that also breaks it (maybe for
historic reasons) — although this is also an opportunity to clean up
someone else’s mess (in true XP style).
Use 2 spaces per indentation level.
Consistency, however is key. When working on a team, use the accepted
level of indentation for your team.
Never mix tabs and spaces.
The most popular way of indenting Ruby is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively.
For new projects, spaces-only are strongly recommended over tabs. Most
editors have features that make this easy to do. A reason to not mix tabs is
spaces can be seen with the following code example:
my_variable = if some_boolean_method?
true_case
else
false_case
end
The indented lines are meant to follow proper if/else formatting. With tabs
enabled, this formatting can become mangled, thus damaging readibility.