Let's summarize the Python coding standard PEP8 (2)

Summary of Python coding standard PEP8 (1) Continued

comment

Block comment

Block comments (#) generally apply to some code that follows and indent to the same level as that code.

Inline comment

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

Documentation strings (also known as “docstrings”)

You should write a docstring for every module, function, class or method.

Naming convention

The most important principle

Use a name that reflects usage rather than implementation

Practical naming method

b (1 lowercase letter)
B (1 uppercase letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
CapitalizedWords

Naming conventions to follow

• 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

Inheritance design

-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.

Public and internal interfaces

• 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

Programming recommendations

· 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:

Function annotation

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.

in conclusion

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

Let's summarize the Python coding standard PEP8 (1)
Let's summarize the Python coding standard PEP8 (2)
[Python coding standard] PEP 8 vs Google Style
Building an environment to comply with the Python coding standard (PEP8) with Eclipse + PyDev
[Python] Adjusted the color map standard
[Blender x Python] Let's master the material !!
Let's read the RINEX file with Python ①
Let's observe the Python Logging cookbook SocketHandler
[Python] Summarize the rudimentary things about multithreading
python> coding guide> PEP 0008 --Style Guide for Python Code
Python amateurs try to summarize the list ①
Let's summarize the construction of NFS server
From Python 3.4, pip becomes the standard installer! ??
Japanese translation: PEP 20 --The Zen of Python
Introduction to Python Let's prepare the development environment
Let's parse the git commit log in Python!
[Python] Let's execute the module regularly using schedule
[Python] Standard input
Let's summarize Squid
First Python ~ Coding 2 ~
A python amateur tries to summarize the list ②
Let's summarize Apache
Summarize Python import
Sort in Python. Next, let's think about the algorithm.
HoloViews may become the standard for Python visualization tools
Have python parse the json entered from the standard input
Let's break down the basics of TensorFlow Python code
Let's use the Python version of the Confluence API module.
Let's use the open data of "Mamebus" in Python
[Python] Let's remember the new writing style after pip10
[Python] Let's change the URL of the Django administrator site
I tried to summarize the string operations of Python
Find the maximum Python
the zen of Python
[Python] Split the date
[Python] About standard input
Let's review the language specifications around Python iterators and generators
How to debug the Python standard library in Visual Studio
Change the standard output destination to a file in Python
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo
(Python3) No. oO (Are you using the standard library?): 5 shaders
Python> coding rule> PEP8> read_chpoint.py: 20: 1: E302 expected 2 blank lines, found 1