An article shows you how these big companies in Google write python code

  • 2021-12-04 10:18:38
  • OfStack

Directory Google internal python code specification 1. Import modules and packages, do not import individual classes, functions or variables. 2. Import from the root directory, without assuming any sys. path, and without using relative imports. 3. Use exceptions with caution 4. Do not use mutable types as function defaults; If you modify this variable, the defaults will change accordingly. 5. Pay attention to the implicit Boolean values of conditional expressions 6. Use decorators carefully 7. Type declarations are recommended, and the benefits of type declarations are obvious: summary

Google internal python code specification

Familiar with python 1 will try to follow pep 8 specification, and some companies will formulate internal code specifications. The purpose of big companies is not to say how you use the programming language, but to make everyone abide by the same set of rules, save others the cost of reading code, and facilitate collaboration and communication. For individuals, it is a great victory to write code in daily life only by keeping the style 1, before and after 1, and then add some practical rules to effectively reduce the possible introduction of bug when writing code.

Next, I intercepted some interesting points from Google's python code specification, hoping to feel their usefulness more deeply in the future.

1. Import modules and packages, not individual classes, functions, or variables.

This usually simplifies the import process and facilitates namespace management. But the drawback is also obvious. When the name is long, the code that calls the function and class will be long, which affects readability.


  # yes
from sound.effects import echo
echo.EchoFilter()
 
# no
from sound.effects.echo import EchoFilter
EchoFilter()

2. Import from the root directory, without assuming any sys. path, and without using relative imports.

Assuming that the doctor. who path has been somehow added to sys. path, it should also be imported from where it started.


  # yes
from doctor.who import jodie
 
# other than doctor.who is already in sys.path
# no
import jodie

3. Use exceptions carefully

Details to pay attention to when using exceptions are:

Give priority to the reasonable use of built-in exception classes. For example, if a positive number is needed, an error caused by a negative number is passed, and ValueError type is thrown. Never use except to catch all exceptions, which may make some hidden bug difficult to find. You should use specific exception types to catch separately. Do not use assert to indicate some unexpected situations, but use raise. Don't add too much logic to the try and except clauses, the larger the try block, the easier it is for unexpected exceptions to be triggered.

Try to use the correct built-in exception types:


  def division(a, b):
    if b == 0:
        raise ValueError('b can not be zero')

Avoid global catch exceptions by specifying exception types:


  # yes
try:
    1 / 0
    "abc"[100]
except ZeroDivisionError:
    ...
except IndexError:
    ...
 
# no
try:
    1 / 0
    "abc"[100]
except:
    ...

4. Do not use mutable type as the default value of the function. If you modify this variable, the default value will change accordingly.


  # yes
def foo(a, b=None):
    if b is None:
        b = []
def foo(a, b: Sequence = ()):
 
# no
def foo(a, b=[]):
def foo(a, b=time.time()):
def foo(a, b={}):

5. Note the implicit Boolean values of conditional expressions

For sequences (string, list, tuple), note that the empty sequence is False. When judging whether it is an empty sequence, use the implicit if not seq instead of if len (seq) = = 0; To determine whether the number is 0, use number = = 0 instead of if not number. Because number may set the default value to None. x is None is used instead of not x for judging whether it is None.

  # yes
.if not users: # sequence
if number == 0:
if i % 10 == 0:
def f(x=None):
    if x is None:
 
# no
if len(users) == 0:
if number is not None and not number:
if not i % 10:
def f(x=None):
    x = x or []

Step 6 Use decorators carefully

The decorator can do anything on the arguments or return values of a function, which can lead to surprising hidden behavior. Moreover, the decorator executes at import time, and it is difficult to catch errors from the decorator code and handle them. To use Decorator 1, you must write a unit test, and explain its function and usage. The decorator itself does not depend on any file, socket, database connection. Avoid using the @ staticmedthod decorator. In most cases, encapsulating methods as module-level functions will achieve the same effect.

7. It is recommended to use type declarations, the benefits of which are obvious:

Using type declaration can improve the readability of code. You can also use the type checking tool to find problems early. With type declarations, there is no need to describe parameter types in doc string. Code prompts are given in the editor according to the type.

However, in practice, type declarations are often difficult to maintain. When the code is updated, 1 remember to update the type declaration, because outdated type declarations will mislead readers. The type declaration cost of python is higher.


  # yes
name: str = 'yuz'
def func(a: int) -> List[int]:

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: