Summary of Python coding standard PEP8 (1) Continued
Block comments (#) generally apply to some code that follows and indent to the same level as that code.
Leave at least two spaces between the statement and the inline comment. No need for in-line comments that are self-explanatory.
bad example:
x = x + 1 #Increase x by 1
You should write a docstring for every module, function, class or method.
Use a name that reflects usage rather than implementation
b (1 lowercase letter)
B (1 uppercase letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
CapitalizedWords
• Do not use the single letters ‘l’ (lowercase el), ‘O’ (uppercase o), and ‘I’ (uppercase eye) as variables. -The module name should be a short name in all lowercase letters. -Use the CapWords method (capitalize the first letter of the word and connect it) for the name of the class -Intra-module limited global variables are prefixed with an underscore (_) to clearly indicate that they are not disclosed to the outside. -Function names should be in lowercase only -Always use self as the name of the first argument of the instance method -Always use cls for the name of the first argument of the class method -Use only lowercase method names and instance variables, and separate words with underscores if necessary. -Write constants in uppercase and separate words with underscores
-Do not add an underscore at the beginning of public attributes -If the name of the published attribute conflicts with the reserved word, add an underscore immediately after the name of the attribute. · Use properties to hide the implementation of function calls with a simple data access syntax -If there is an attribute that you do not want to use in the subclass, add two underscores at the beginning of the name instead of the end.
• A documented interface is considered a public interface unless the document explicitly declares it to be an internal interface. · Internal interfaces (packages, modules, classes, functions, attributes, other names) have one underscore in front of the name
· Write code that is not disadvantageous to other Python implementations (PyPy, Jython, IronPython, Cython, Psyco, etc.)
· Always use is or is not when comparing with None
-All operations when implementing sorting using extended comparison
(__eq__, __ne__, __lt__, __le__, __gt__, __ge__)
To implement
· Always use a def statement instead of writing an assignment statement that connects a lambda expression directly to an identifier
Good example:
def f(x): return 2*x
bad example:
f = lambda x: 2*x
· Try to derive an exception from an Exception instead of a BaseException · Python3 uses “raise X from Y” to explicitly replace exceptions without losing the original traceback -Use raise ValueError ('message') to raise an exception in Python2 -When catching an exception, specify a specific exception instead of the raw except: which does not specify an exception.
Like this
try:
import platform_specific_module
except ImportError:
platform_specific_module = None
-If you want to associate the caught exception with a specific name, explicitly name the exception
Like this
try:
process_data()
except Exception as exc:
raise DataProcessingFailedError(str(exc))
· Explicitly use the new operating system-related error hierarchy when catching operating system errors -For all try / except, limit the range enclosed by try to the minimum necessary code.
Good example:
try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
bad example:
try:
#The process of enclosing in try is too large
return handle_value(collection[key])
except KeyError:
# handle_value()Also catches the KeyError generated by
return key_not_found(key)
· Use the with statement if the resource is used only in a specific part of the code ・ Write the return statement consistently. -If there is a return statement in the function that returns an expression, the return statement that returns no value is explicitly written as return None. -Use string methods rather than string modules · To check if a string has a specific prefix or suffix, use'' .startswith () and''.endswith () instead of string slicing.
Good example: if foo.startswith('bar'):
bad example: if foo[:3] == 'bar':
-Always use isinstance () to compare object types instead of comparing types directly.
Good example: if isinstance(obj, int):
bad example: if type(obj) is type(1):
-For sequences, use the fact that the empty sequence is False.
Good example: if not seq:
if seq:
bad example: if len(seq):
if not len(seq):
-Do not write string literals that depend on whitespace characters at the end of lines · Stop using == to compare Boolean values with True or False
Good example: if greeting:
bad example: if greeting == True:
Worse example: if greeting is True:
Code that wants to use function annotations in a different style than PEP484 (https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code) about,
type: ignore
Is written near the beginning of the file. This tells the type checking program to ignore all annotations.
If you just understand that it is written in that way, I think that this level of content is sufficient. If you want to know more (why you should write it that way), please refer to Documentation.
Recommended Posts