PEP 8: Fix inconsistent use of line breaks, case and indentation (#664)

This commit is contained in:
Géry Ogam 2018-07-08 01:20:37 +02:00 committed by Guido van Rossum
parent 7eb19d4388
commit 3714aa1cef
1 changed files with 36 additions and 51 deletions

View File

@ -68,7 +68,7 @@ Some other good reasons to ignore a particular guideline:
Python that don't support the feature recommended by the style guide.
Code lay-out
Code Lay-out
============
Indentation
@ -179,7 +179,6 @@ starts the multiline construct, as in::
'd', 'e', 'f',
)
Tabs or Spaces?
---------------
@ -198,7 +197,6 @@ the ``-t`` option, it issues warnings about code that illegally mixes
tabs and spaces. When using ``-tt`` these warnings become errors.
These options are highly recommended!
Maximum Line Length
-------------------
@ -249,7 +247,6 @@ Another such case is with ``assert`` statements.
Make sure to indent the continued line appropriately.
Should a Line Break Before or After a Binary Operator?
------------------------------------------------------
@ -287,7 +284,6 @@ In Python code, it is permissible to break before or after a binary
operator, as long as the convention is consistent locally. For new
code Knuth's style is suggested.
Blank Lines
-----------
@ -309,7 +305,6 @@ you may use them to separate pages of related sections of your file.
Note, some editors and web-based code viewers may not recognize
control-L as a form feed and will show another glyph in its place.
Source File Encoding
--------------------
@ -339,11 +334,10 @@ a transliteration of their names in this character set.
Open source projects with a global audience are encouraged to adopt a
similar policy.
Imports
-------
- Imports should usually be on separate lines, e.g.::
- Imports should usually be on separate lines::
Yes: import os
import sys
@ -370,16 +364,16 @@ Imports
messages) if the import system is incorrectly configured (such as
when a directory inside a package ends up on ``sys.path``)::
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example
However, explicit relative imports are an acceptable alternative to
absolute imports, especially when dealing with complex package layouts
where using absolute imports would be unnecessarily verbose::
from . import sibling
from .sibling import example
from . import sibling
from .sibling import example
Standard library code should avoid complex package layouts and always
use absolute imports.
@ -393,7 +387,7 @@ Imports
from myclass import MyClass
from foo.bar.yourclass import YourClass
If this spelling causes local name clashes, then spell them ::
If this spelling causes local name clashes, then spell them explicitly::
import myclass
import foo.bar.yourclass
@ -412,8 +406,7 @@ Imports
When republishing names this way, the guidelines below regarding
public and internal interfaces still apply.
Module level dunder names
Module Level Dunder Names
-------------------------
Module level "dunders" (i.e. names with two leading and two trailing
@ -421,9 +414,7 @@ underscores) such as ``__all__``, ``__author__``, ``__version__``,
etc. should be placed after the module docstring but before any import
statements *except* ``from __future__`` imports. Python mandates that
future-imports must appear in the module before any other code except
docstrings.
For example::
docstrings::
"""This is the example module.
@ -524,7 +515,6 @@ Avoid extraneous whitespace in the following situations:
y = 2
long_variable = 3
Other Recommendations
---------------------
@ -642,6 +632,7 @@ Other Recommendations
if foo == 'blah': one(); two(); three()
When to Use Trailing Commas
===========================
@ -748,7 +739,7 @@ Conventions for writing good documentation strings
- PEP 257 describes good docstring conventions. Note that most
importantly, the ``"""`` that ends a multiline docstring should be
on a line by itself, e.g.::
on a line by itself::
"""Return a foobang
@ -888,12 +879,12 @@ Type Variable Names
Names of type variables introduced in PEP 484 should normally use CapWords
preferring short names: ``T``, ``AnyStr``, ``Num``. It is recommended to add
suffixes ``_co`` or ``_contra`` to the variables used to declare covariant
or contravariant behavior correspondingly. Examples::
or contravariant behavior correspondingly::
from typing import TypeVar
from typing import TypeVar
VT_co = TypeVar('VT_co', covariant=True)
KT_contra = TypeVar('KT_contra', contravariant=True)
VT_co = TypeVar('VT_co', covariant=True)
KT_contra = TypeVar('KT_contra', contravariant=True)
Exception Names
~~~~~~~~~~~~~~~
@ -966,7 +957,7 @@ Constants are usually defined on a module level and written in all
capital letters with underscores separating words. Examples include
``MAX_OVERFLOW`` and ``TOTAL``.
Designing for inheritance
Designing for Inheritance
~~~~~~~~~~~~~~~~~~~~~~~~~
Always decide whether a class's methods and instance variables
@ -1041,7 +1032,6 @@ With this in mind, here are the Pythonic guidelines:
need to avoid accidental name clashes with potential use by
advanced callers.
Public and Internal Interfaces
------------------------------
@ -1180,9 +1170,7 @@ Programming Recommendations
continuation characters thanks to the containing parentheses.
- When catching exceptions, mention specific exceptions whenever
possible instead of using a bare ``except:`` clause.
For example, use::
possible instead of using a bare ``except:`` clause::
try:
import platform_specific_module
@ -1250,17 +1238,16 @@ Programming Recommendations
- Context managers should be invoked through separate functions or methods
whenever they do something other than acquire and release resources.
For example:
Yes::
with conn.begin_transaction():
do_stuff_in_transaction(conn)
with conn.begin_transaction():
do_stuff_in_transaction(conn)
No::
with conn:
do_stuff_in_transaction(conn)
with conn:
do_stuff_in_transaction(conn)
The latter example doesn't provide any information to indicate that
the ``__enter__`` and ``__exit__`` methods are doing something other
@ -1307,8 +1294,7 @@ Programming Recommendations
- Use ``''.startswith()`` and ``''.endswith()`` instead of string
slicing to check for prefixes or suffixes.
startswith() and endswith() are cleaner and less error prone. For
example::
startswith() and endswith() are cleaner and less error prone::
Yes: if foo.startswith('bar'):
No: if foo[:3] == 'bar':
@ -1328,7 +1314,7 @@ Programming Recommendations
Note that in Python 3, ``unicode`` and ``basestring`` no longer exist
(there is only ``str``) and a bytes object is no longer a kind of
string (it is a sequence of integers instead)
string (it is a sequence of integers instead).
- For sequences, (strings, lists, tuples), use the fact that empty
sequences are false. ::
@ -1336,8 +1322,8 @@ Programming Recommendations
Yes: if not seq:
if seq:
No: if len(seq):
if not len(seq):
No: if len(seq):
if not len(seq):
- Don't write string literals that rely on significant trailing
whitespace. Such trailing whitespace is visually indistinguishable
@ -1375,7 +1361,7 @@ annotations are changing.
- For code that wants to make a different use of function annotations
it is recommended to put a comment of the form::
# type: ignore
# type: ignore
near the top of the file; this tells type checker to ignore all
annotations. (More fine-grained ways of disabling complaints from
@ -1397,7 +1383,7 @@ annotations are changing.
can be added in the form of comments. See the relevant section of
PEP 484 [6]_.
Variable annotations
Variable Annotations
--------------------
PEP 526 introduced variable annotations. The style recommendations for them are
@ -1413,19 +1399,19 @@ similar to those on function annotations described above:
- Yes::
code: int
code: int
class Point:
coords: Tuple[int, int]
label: str = '<unknown>'
class Point:
coords: Tuple[int, int]
label: str = '<unknown>'
- No::
code:int # No space after colon
code : int # Space before colon
code:int # No space after colon
code : int # Space before colon
class Test:
result: int=0 # No spaces around equality sign
class Test:
result: int=0 # No spaces around equality sign
- Although the PEP 526 is accepted for Python 3.6, the variable annotation
syntax is the preferred syntax for stub files on all versions of Python
@ -1460,7 +1446,6 @@ References
https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
Copyright
=========