工具
- pep8检查工具
- pylint
- pre-commit
import 顺序问题
- 标准库导入
- 第三方相关包导入
- 本地应用或库导入
# 标准库
from math import sqrt
from os.path import abspath
# Django导入
from django.db import models
from django.utils.translation import ugettext_lazy as _
# 第三方应用导入
from rest_framework.response import Response
# 导入自己的应用
from user.models import User
- 尽量不要使用
id
type
等Python关键字给变量命名
代码的坏味道
- 神奇的数字 使用常量代替
# 神奇的数字
def func(state):
if state == 2:
return 5
if state == 3:
return 10
return 13
- 确定不会再使用的代码,别注释掉,直接删除
- 重复的代码 DRY
- 不必要的复杂
- 不知所云的变量名
- 冗长的类
- 过长的函数
防御性编程
- 最小权限原则
- 所有的数据输入是否都进行了检查(检测正确的类型,长度,格式和范围)并且进行了编码,无效的参数值是否能够处理?考虑边界值
- 在哪里使用了第三方工具,返回的异常是否被捕获?
- 输出的值是否进行了检查并且编码?
- 对非常规行为和边界情况是否进行了处理
编写函数的几个原则
- 1:函数设计要尽量短小,嵌套层次不宜过深。最好能控制在 3 层以内。
- 2:函数申明应该做到合理、简单、易于使用。参数个数不宜太多。
- 3:函数参数设计应该考虑向下兼容。比如相同功能的函数不同版本的实现,唯一不同的是在更高级的版本中添加了参数导致程序中函数调用的接口发生了改变。这并不是最佳设计,更好的方法是通过加入默认参数来避免这种退化,做到向下兼容。
- 4:一个函数只做一件事,尽量保证函数语句粒度的一致性。(同理类设计也一样,一个类只做一件事)
- 5:不要在函数参数中定义可变对象作为默认值(除非你确定自己需要这么做)
- 6:使用异常替换返回错误(依情况而定)
- 7:保证通过单元测试
阅读清单
- PEP8 https://www.python.org/dev/peps/pep-0008/
- Python风格规范 http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/
- Python语言规范 http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_language_rules/
- Python Code Style http://www.wklken.me/posts/2016/11/03/python-code-style.html
- https://pythonguidecn.readthedocs.io/zh/latest/writing/style.html
- http://www.wklken.me/posts/2016/11/03/python-code-style.html
pylint检测代码规范
pre-commit代码提交前检查
.pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v1.4.0
hooks:
- id: trailing-whitespace
exclude: '^restdocs/'
- id: end-of-file-fixer
exclude: '^restdocs/'
- id: autopep8-wrapper
exclude: \/migrations\/
- id: check-docstring-first
- id: check-json
- id: check-added-large-files
- id: check-yaml
- id: debug-statements
- id: requirements-txt-fixer
- repo: https://github.com/pre-commit/pre-commit
rev: v1.11.0
hooks:
- id: validate_manifest
- repo: local
hooks:
- id: pylint
name: pylint
entry: pylint
language: system
files: \.py$
exclude: '((migrations)/|(fabfile.py$))|((docs)/)'
args: [--rcfile=.pylintrc, --load-plugins=pylint_django]
.pre-commit-hooks.yaml
- id: validate_manifest
name: Validate Pre-Commit Manifest
description: This validator validates a pre-commit hooks manifest file
entry: pre-commit-validate-manifest
language: python
files: ^(\.pre-commit-hooks\.yaml|hooks\.yaml)$