Code practice

1 Python

1.1 避免魔术数字

不要在代码中出现 Magic Number

# BAD
if cluster_type == 1:
    pass


# GOOD
class enum_cluster_type(object):
    """"""
    K8S = 1
    Mesos = 2

if cluster_type == enum_cluster_type.K8S:
    pass

1.2 不要预计算字面量表达式

如果某个变量是通过简单算式得到的,应该保留算式内容。不要直接使用计算后的结果。

# BAD
if delta_seconds > 950400:
    return

# GOOD
if delta_seconds > 11 * 24 * 3600:
    return

1.3 优先使用列表推导或内联函数

使用列表推导或内联函数能够清晰知道要生成一个列表,并且更简洁

# BAD
list_two = []
for v in list_one:
    if v[0]:
        new_list.append(v[1])

# GOOD one
list_two = [v[1] for v in list_one if v[0]]

# GOOD two
list_two = list(filter(lambda x: x[0], list_one))

1.4 当在非测试代码中使用 assert 时,妥善添加断言信息

>>> assert 1 == 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

在大段的日志中,单独存在的 AssertionError 不利于日志检索和问题定位,所以添加上可读的断言信息是更推荐的做法。

# BAD
assert "hello" == "world"

# GOOD
assert "hello" == "world", "Hello is not equal to world"

eg:

assert isinstance(req, Request), "req must request"

2 Butterfly

2.1 command 执行时默认展示 table,接口请求时展示 json

参数默认值设置为 "table",程序内部判断当前请求方式

if req.wsgienv.get("REQUEST_METHOD", "COMMAND") != "COMMAND":
    display = "json"

Last updated