Chapter 3 Python Style Guide
3.2 Naming Conventions
module_name
, package_name
, ClassName
, method_name
, ExceptionName
,
function_name
, GLOBAL_CONSTANT_NAME
, global_var_name
, instance_var_name
,
function_parameter_name
, local_var_name
.
Function names, variable names, and filenames should be descriptive. In particular, do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word.
3.2.1 Names to Avoid
- single character names, except for specifically allowed cases:
- counters or iterators (e.g.
i
,j
,k
,v
, et al.). e
as an exception identifier in try/except statements.f
as a file handle in with statements.
- counters or iterators (e.g.
- dashes (
-
) in any package/module name. __double_leading_and_trailing_underscore__
names (reserved by Python).
3.2.2 File Naming
Python filenames must have a .py
extension and must not contain dashes (-
).
3.2.2.1 Naming guides from google python style
Type | Public | Internal |
---|---|---|
Packages | lower_with_under |
|
Classes | CapWords |
_CapWords |
Exceptions | CapWords |
|
Functions | lower_with_under() |
lower_with_under() |
Global/Class Constants | CAPS_WITH_UNDER |
_CAPS_WITH_UNDER |
Global/Class Variables | lower_with_under |
_lower_with_under |
Instance Variables | lower_with_under |
_lower_with_under |
Method Names | lower_with_under() |
_lower_with_under() |
Function/Method Parameters | lower_with_under |
|
Local Variables | lower_with_under |
3.3 Code Layout
3.3.1 Line length
Maximum line length is 80 characters.
Explicit exceptions to the 80 character limit:
- Long import statements.
- URLs, pathnames, or long flags in comments.
When a literal string won’t fit on a single line, use parentheses for implicit line joining.
Python will assume line continuation if code is contained within parentheses, brackets, or braces:
If it is impossible to use implied continuation, then you can use backslashes to break lines instead. However, if you can use implied continuation, then you should do so.
If line breaking needs to occur around binary operators, like + and *, it should occur before the operator.
3.3.2 Indentation
Use 4 spaces per indentation level.
Prefer spaces over tabs.
Never use tabs or mix tabs and spaces.
# Aligned with opening delimiter. foo = long_function_name(var_one, var_two, var_three, var_four) # Add 4 spaces (an extra level of indentation) to distinguish arguments from # the rest. def long_function_name( var_one, var_two, var_three, var_four): print(var_one) # Hanging indents should add a level. foo = long_function_name( var_one, var_two, var_three, var_four)
3.3.3 Parentheses
Use parentheses around tuples.
Do not use them in return statements or conditional statements unless using parentheses for implied line continuation or to indicate a tuple.
3.3.4 Blank Lines
Two blank lines between top-level definitions, be they function or class definitions.
One blank line between method definitions inside classes.
Use single blank lines as you judge appropriate within functions or methods.
3.3.5 Whitespace
No whitespace inside parentheses, brackets or braces.
No whitespace before a comma, semicolon, or colon. Do use whitespace after a comma, semicolon, or colon, except at the end of the line.
No whitespace before the open paren/bracket that starts an argument list, indexing or slicing.
Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
Never use spaces around = when passing keyword arguments or defining a default parameter value, with one exception: when a type annotation is present, do use spaces around the = for the default parameter value.
3.3.6 Trailing Commas
Trailing commas in sequences of items are recommended only when the closing
container token ]
, )
, or }
does not appear on the same line as the final
element.
3.3.7 Strings
Use an
f-string
, the%
operator, or theformat
method for formatting strings, even when the parameters are all strings.Use your best judgment to decide between + and % (or format) though.
Do not use % or the format method for pure concatenation.
# good x = '%s, %s!' % (imperative, expletive) x = '{}, {}'.format(first, second) x = 'name: %s; score: %d' % (name, n) x = 'name: {}; score: {}'.format(name, n) x = f'name: {name}; score: {n}' # bad x = '%s%s' % (a, b) # use + in this case x = '{}{}'.format(a, b) # use + in this case x = first + ', ' + second x = 'name: ' + name + '; score: ' + str(n)
Be consistent with your choice of string quote character within a file. Pick
'
or"
and stick with it. It is okay to use the other quote character on a string to avoid the need to backslash-escape quote characters within the string.Prefer
"""
for multi-line strings rather than'''
.Multi-line strings do not flow with the indentation of the rest of the program. If you need to avoid embedding extra space in the string, use concatenated single-line strings.
3.3.8 Imports
Imports should usually be on separate lines.
Imports are always put at the top of the file, just after any module comments and docstrings and before module globals and constants. Imports should be grouped in the following order, and you should put a blank line between each group of imports.
Standard library imports.
Related third party imports.
Local application/library specific imports.
3.1 Comments and Docstrings
You should use comments to document code as it’s written. It is important to document your code so that you, and any collaborators, can understand it. When you or someone else reads a comment, they should be able to easily understand the code the comment applies to and how it fits in with the rest of your code.
3.1.1 Block Comments
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a
#
and a single space (unless it is indented text inside the comment).Paragraphs inside a block comment are separated by a line containing a single #.
3.1.2 Inline Comments
Use inline comments sparingly.
An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a
#
and a single space.Inline comments are unnecessary and in fact distracting if they state the obvious. Don’t do this:
But sometimes, this is useful:
3.1.3 Docstrings
Write docstrings for all public modules, functions, classes, and methods.
Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.
Surround docstrings with three double quotes on either side, as in ""“This is a docstring”"".
Put the """ that ends a multiline docstring on a line by itself:
For one liner docstrings, please keep the closing """ on the same line:
Recommend to use Numpy Docstring format. An example from numpy: