Python风格规范

2017-11-09  本文已影响0人  NoFacePeace

为了便于项目的管理和代码的阅读,养成良好的编码风格以及沟通方便,编码Python代码时应遵循以下编码规范:

x = ('This will build a long long long long '
     'long long long long string')
# -*- coding: utf-8 -*-
# 可以在编辑器中设置Tab的缩进和文件编码
#!/usr/bin/env python
#!/usr/bing/python2.7

注:在计算机科学中,Shebang是由一个井号和感叹号构成的字符串(#!),其出现在文本的第一行的前两个字符.在文本中存在Shebang的情况下,类Unix操作系统的程序载入器会分析shebang后的内容,将这些词作为解释器命令,并调用该指令,并将载有Shebang的文件路径作为该解释器的参数.

def logic_get_client_basic_info(client_list, fields, from_third_party=False):
    """
    Return a list of clients with basic information.

    Args:
        client_list: Client list, each element is a dict
        fields: Information fields to be returned
        from_third_party: If get basic info from third party open api. Note that
            if set this True, it will slow down the return speed

    Returns:
        A list of clients, fill with company basic information

    """
    names = list()
    client_dict = dict()

    for client in client_list:
        names.append(client[Customer.ContactField.name])
        client_dict[client[Customer.ContactField.name]] = client

    enterprises = list(Enterprise.s_col.find(
        {
            Enterprise.Field.name: {'$in': names}
        },
        fields
    ))
    found_names = list()
    for enterprise in enterprises:
        # 这里一定要使用 Enterprise 模型中的 name 字段替换搜索系统中的
        # name 字段,因为同一个公司可能在搜索系统中有几个名字,但是只有
        # 一个名字在 Enterprise 模型中存在
        name = enterprise[Enterprise.Field.name]
        found_names.append(name)
        enterprise.pop('_id')
        client_dict[name].update(enterprise)

    if from_third_party:
        # Check those names that not found
        lack_names = [_ for _ in names if _ not in found_names]
        ok, company_dict = logic_get_companies_by_fullname(lack_names)
        if ok:
            logic_update_into_enterprises(company_dict)

        lack_enterprises = list(Enterprise.s_col.find(
            {
                Enterprise.Field.name: {'$in': names}
            },
            fields
        ))
        for enterprise in lack_enterprises:
            name = enterprise[Enterprise.Field.name]
            enterprise.pop('_id')
            client_dict[name].update(enterprise)

    return [client_dict[_] for _ in names]

API或Model的注释用Markdown格式书写,方便调用脚本直接生成wiki,注释示例如下:

@api.route('/user', methods=['POST'])
def create_user():
    """
    ## Create User
    Extra information to describe this api.

        POST '/api/user'

    Params:
    * `username` (string) - User name
    * `password` (string) - Md5 user password
    * `signature` (string) *optional* - User signature

    Returns:
    * `_id` - New user id

    Errors: `1001`, `1002`

    ---
    """
    pass
import os
import sys

from flask import (
  jsonify,
  request,
)

from logic.user import logic_get_user
from model.user import User

导入模块统一使用绝对路径.只导入需要的模块,应该避免

from . import xxx
from xxx.xxx import *

这种导入方式

上一篇 下一篇

猜你喜欢

热点阅读