智伤帝的个人博客

智伤帝

马上订阅 智伤帝的个人博客 RSS 更新: https://blog.l0v0.com/atom.xml

Python 代码规范

2022年5月9日 11:16

Python 编程规范系列大纲

  1. Python 代码规范
    1. flake8 代码检查工具
    2. wemake python style
  2. Python poetry 包管理
  3. Python 工具配置
    1. commitizen
    2. isort
    3. black
    4. pylint
    5. falkehell
    6. pre-commit
    7. tox & nox 测试环境管理
  4. Python mkdocs 文档构建
  5. Python pytest 单元测试
  6. Python cookiecutter 项目模板生成工具
  7. Python Github 开源项目维护流程
    1. Github Action
    2. pull request
    3. git rebase 说明

前言

  过去在项目组开发,需要快速迭代,通常都是面向美术编程,这个需要快准狠地解决问题,至于代码怎么写其实是没有任何要求的。
  但是这对于长线维护来说简直是灾难,当这种代码越来越多之后,就会变成一堆没人敢碰的屎山代码。
  那怎么才能写出可以长期维护的代码呢?
  下面我会开一个 Python 编程规范 系列,整理出一整套 Python 的编程规范,以及配套的工具。
  这个过程是这小半年来的一次总结,这里诚挚地感谢我的同事 龙浩 ,它教会了很多~

Python 代码规范

  1. 谷歌规范 styleguide | Style guides for Google-originated open-source projects
  2. Maya Python 开发规范: Python Scripting for Maya Artists | Chad Vernon
  3. TA 101: theodox/ta_101: a coding standards doc for technical artists (github.com)

  其中我结合自身理解,翻译了 Maya Python 开发规范TA 101,大家可以自行参阅。

文件头部统一写法

  我们的代码优先采用 Python3 写法,因此根据谷歌规范,所有的代码文件需要加上下列规范
  __future__ 模块用来兼容 Python3 写法
  coding:utf-8 兼容 utf-8 编码

1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-
"""
module docstring
"""

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

  from __future__ import division 可以引入整数相除可以得到小数 (Python2的默认环境是得到整数)
  from __future__ import print_function 可以让 print 关键字变为 Python3 的 print 方法,可以在 lambda 里面使用 print
  **from __future__ import absolute_import 引入绝对导入

  division 会导致 OpenMaya 一些类型的运算符失效

PowerPoint プレゼンテーション (square-enix.com)

  原因是引入 division 之后 除法 除法 __truediv__ 而不再是 __div__ 了

enter image description here

backport 兼容库

six - py2 & py3 兼容

Github: benjaminp/six: Python 2 and 3 compatibility...