查看原文
其他

代码整洁之道-编写 Pythonic 代码

陈祥安 Python大本营 2019-06-21

作者 | 陈祥安

编辑 | suiling

出品 | Python学习开发(ID:python3-5)


很多新手在开始学一门新的语言的时候,往往会忽视一些不应该忽视的细节,比如变量命名和函数命名以及注释等一些内容的规范性,久而久之养成了一种习惯。对此呢,我特意收集了一些适合所有学习 Python 的人,代码整洁之道。

写出 Pythonic 代码

谈到规范首先想到就是 Python 有名的 PEP8 代码规范文档,它定义了编写Pythonic代码的最佳实践。可以在 

https://www.python.org/dev/peps/pep-0008/ 上查看。但是真正去仔细研究学习这些规范的朋友并不是很多,对此呢这篇文章摘选一些比较常用的代码整洁和规范的技巧和方法,下面让我们一起来学习吧!

命名

所有的编程语言都有变量、函数、类等的命名约定,以美之称的 Python 当然更建议使用命名约定。 接下来就针对类、函数、方法等等内容进行学习。


变量和函数


使用小写字母命名函数和变量,并用下划线分隔单词,提高代码可读性。


变量的声明


names = "Python" #变量名 
namejob_title = "Software Engineer" #带有下划线的变量名
populated_countries_list = []  #带有下划线的变量名 

还应该考虑在代码中使用非 Python 内置方法名,如果使用 Python 中内置方法名请使用一个或两个下划线()。

_books = {}# 变量名私有化
__dict = []# 防止python内置库中的名称混淆


那如何选择是用_还是__呢?


如果不希望外部类访问该变量,应该使用一个下划线(_)作为类的内部变量的前缀。如果要定义的私有变量名称是 Python 中的关键字如 dict 就要使用(__)。


函数的声明


def get_data(): 
    pass
def calculate_tax_data():
    pass


函数的声明和变量一样也是通过小写字母和单下划线进行连接。

当然对于函数私有化也是和声明变量类似。


def _get_data():
   pass


函数的开头使用单下划线,将其进行私有化。对于使用 Pyton 中的关键字来进行命名的函数


要使用双下划线。


def __path():
    pass


除了遵循这些命名规则之外,使用清晰易懂的变量名和很重要。


函数名规范


# Wrong Way
def get_user_info(id):
   db = get_db_connection()
   user = execute_query_for_user(id)
   return user

# Right way
def get_user_by(user_id):
    db = get_db_connection()
    user = execute_user_query(user_id) 
    return user

这里,第二个函数 get_user_by 确保使用相同的参数来传递变量,从而为函数提供正确的上下文。 第一个函数 get_user_info 就不怎么不明确了,因为参数 id 意味着什么这里我们不能确定,它是用户 ID,还是用户付款ID或任何其他 ID? 这种代码可能会对使用你的API的其他开发人员造成混淆。为了解决这个问题,我在第二个函数中更改了两个东西; 我更改了函数名称以及传递的参数名称,这使代码可读性更高。

作为开发人员,你有责任在命名变量和函数时仔细考虑,要写让人能够清晰易懂的代码。

当然也方便自己以后去维护。

类的命名规范

类的名称应该像大多数其他语言一样使用驼峰大小写。

class UserInformation:
     def get_user(id):
          db = get_db_connection()
          user = execute_query_for_user(id)
          return user


常量的命名规范

通常应该用大写字母定义常量名称。

TOTAL = 56
TIMOUT = 6
MAX_OVERFLOW = 7

函数和方法的参数

函数和方法的参数命名应遵循与变量和方法名称相同的规则。因为类方法将self作为第一个关键字参数。所以在函数中就不要使用 self 作为关键字作为参数,以免造成混淆。

def calculate_tax(amount, yearly_tax):
    passs

class Player:
    def get_total_score(self, player_name):
         pass

关于命名大概就强调这些,下面让我们看看表达式和语句中需要的问题。

代码中的表达式和语句

users = [
    {"first_name":"Helen", "age":39},
    {"first_name":"Buck", "age":10},
    {"first_name":"anni", "age":9}
]
users = sorted(users, key=lambda user: user["first_name"].lower())

这段代码有什么问题?

乍一看并不容易理解这段代码,尤其是对于新开发人员来说,因为 lambdas 的语法很古怪,所以不容易理解。虽然这里使用 lambda 可以节省行,然而,这并不能保证代码的正确性和可读性。同时这段代码无法解决字典缺少键出现异常的问题。

让我们使用函数重写此代码,使代码更具可读性和正确性; 该函数将判断异常情况,编写起来要简单得多。

users = [
    {"first_name":"Helen", "age":39},
    {"first_name":"Buck", "age":10},
    {"name":"anni", "age":9}
]
def get_user_name(users):
    """Get name of the user in lower case"""
    return users["first_name"].lower()
def get_sorted_dictionary(users):
    """Sort the nested dictionary"""
    if not isinstance(users, dict):
        raise ValueError("Not a correct dictionary")
    if not len(users):
       raise ValueError("Empty dictionary")
    users_by_name = sorted(users, key=get_user_name)
    return users_by_name

如你所见,此代码检查了所有可能的意外值,并且比起以前的单行代码更具可读性。 单行代码虽然看起来很酷节省了行,但是会给代码添加很多复杂性。 但是这并不意味着单行代码就不好 这里提出的一点是,如果你的单行代码使代码变得更难阅读,那么就请避免使用它,记住写代码不是为了炫酷的,尤其在项目组中。

让我们再考虑一个例子,你试图读取 CSV 文件并计算 CSV 文件处理的行数。下面的代码展示使代码可读的重要性,以及命名如何在使代码可读中发挥重要作用。

import csv
with open("employee.csv", mode="r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
            print(f'\t{row["name"]} salary: {row["salary"]}'
            f'and was born in {row["birthday month"]}.')
        line_count += 1
    print(f'Processed {line_count} lines.')

将代码分解为函数有助于使复杂的代码变的易于阅读和调试。

这里的代码在 with 语句中执行多项操作。为了提高可读性,您可以将带有 process salary 的代码从 CSV 文件中提取到另一个函数中,以降低出错的可能性。

import csv
with open("employee.csv", mode="r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    process_salary(csv_reader)    


def process_salary(csv_reader):
"""Process salary of user from csv file."""
    for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
                print(f'\t{row["name"]} salary: {row["salary"]}'
                f'and was born in {row["birthday month"]}.')
            line_count += 1
        print(f'Processed {line_count} lines.') 

代码是不是变得容易理解了不少呢。

在这里,创建了一个帮助函数,而不是在with语句中编写所有内容。这使读者清楚地了解了函数的实际作用。如果想处理一个特定的异常或者想从CSV文件中读取更多的数据,可以进一步分解这个函数,以遵循单一职责原则,一个函数一做一件事,这个很重要。

return语句的类型尽量一致

如果希望函数返回一个值,请确保该函数的所有执行路径都返回该值。但是,如果期望函数只是在不返回值的情况下执行操作,则 Python 会隐式返回 None 作为函数的默认值。

先看一个错误示范:

def calculate_interest(principle, time rate):    
     if principle > 0:
         return (principle * time * rate) / 100
def calculate_interest(principle, time rate):    
    if principle < 0:
        return    
    return (principle * time * rate) / 100ChaPTER 1  PyThonIC ThInkIng

正确的示范应该是下面这样

def calculate_interest(principle, time rate):    
     if principle > 0:
         return (principle * time * rate) / 100
     else:
        return None
def calculate_interest(principle, time rate):    
    if principle < 0:
        return None    
    return (principle * time * rate) / 100ChaPTER 1  PyThonIC ThInkIng

还是那句话写易读的代码,代码多写点没关系,可读性很重要。

使用 isinstance() 方法而不是 type() 进行比较

当比较两个对象类型时,请考虑使用 isinstance() 而不是 type,因为 isinstance() 判断一个对象是否为另一个对象的子类是 true。考虑这样一个场景:如果传递的数据结构是dict 的子类,比如 orderdict。type() 对于特定类型的数据结构将失败;然而,isinstance() 可以将其识别出它是 dict 的子类。

错误示范

user_ages = {"Larry": 35, "Jon": 89, "Imli": 12}
type(user_ages) == dict:

正确选择

user_ages = {"Larry": 35, "Jon": 89, "Imli": 12}
if isinstance(user_ages, dict):

比较布尔值

在Python中有多种方法可以比较布尔值。
错误示范

if is_empty = False
if is_empty == False:
if is_empty is False:

正确示范

is_empty = False
if is_empty

使用文档字符串

Docstrings可以在 Python 中声明代码的功能的。通常在方法,类和模块的开头使用。 docstring是该对象的__doc__特殊属性。
Python 官方语言建议使用“”三重双引号“”来编写文档字符串。 你可以在 PEP8 官方文档中找到这些实践。 下面让我们简要介绍一下在 Python 代码中编写 docstrings 的一些最佳实践 。

方法中使用docstring


def get_prime_number():
    """Get list of prime numbers between 1 to 100.""""

关于docstring的格式的写法,目前存在多种风格,但是这几种风格都有一些统一的标准。

  • 即使字符串符合一行,也会使用三重引号。当你想要扩展时,这种注释非常有用。

  • 三重引号中的字符串前后不应有任何空行

  • 使用句点(.)结束docstring中的语句
    类似地,可以应用 Python 多行 docstring 规则来编写多行 docstring。在多行上编写文档字符串是用更具描述性的方式记录代码的一种方法。你可以利用 Python 多行文档字符串在 Python 代码中编写描述性文档字符串,而不是在每一行上编写注释。

多行的docstring


def call_weather_api(url, location):
    """Get the weather of specific location.

    Calling weather api to check for weather by using weather api and 
    location. Make sure you provide city name only, country and county 
    names won't be accepted and will throw exception if not found the 
    city name.

    :param url:URL of the api to get weather.
    :type url: str
    :param location:Location of the city to get the weather.
    :type location: str
    :return: Give the weather information of given location.
    :rtype: str"""

说一下上面代码的注意点

  • 第一行是函数或类的简要描述

  • 每一行语句的末尾有一个句号

  • 文档字符串中的简要描述和摘要之间有一行空白

如果使用 Python3.6 可以使用类型注解对上面的docstring以及参数的声明进行修改。

def call_weather_api(url: str, location: str) -> str:
    """Get the weather of specific location.

    Calling weather api to check for weather by using weather api and 
    location. Make sure you provide city name only, country and county 
    names won't be accepted and will throw exception if not found the 
    city name.
    """

怎么样是不是简洁了不少,如果使用 Python 代码中的类型注解,则不需要再编写参数信息。

关于类型注解(type hint)的具体用法可以参考我之前写的python类型检测最终指南--Typing的使用

模块级别的docstring

一般在文件的顶部放置一个模块级的 docstring 来简要描述模块的使用。

这些注释应该放在在导包之前,模块文档字符串应该表明模块的使用方法和功能。

如果觉得在使用模块之前客户端需要明确地知道方法或类,你还可以简要地指定特定方法或类。

"""This module contains all of the network related requests. 
This module will check for all the exceptions while making the network 
calls and raise exceptions for any unknown exception.
Make sure that when you use this module,
you handle these exceptions in client code as:
NetworkError exception for network calls.
NetworkNotFound exception if network not found.
"""

import urllib3
import json

在为模块编写文档字符串时,应考虑执行以下操作:

  • 对当前模块写一个简要的说明

  • 如果想指定某些对读者有用的模块,如上面的代码,还可以添加异常信息,但是注意不要太详细。

NetworkError exception for network calls.
NetworkNotFound exception if network not found.

  • 将模块的docstring看作是提供关于模块的描述性信息的一种方法,而不需要详细讨论每个函数或类具体操作方法。

类级别的docstring

类docstring主要用于简要描述类的使用及其总体目标。 让我们看一些示例,看看如何编写类文档字符串

单行类docstring

class Student:
   """This class handle actions performed by a student."""
   def __init__(self):
      pass

这个类有一个一行的 docstring,它简要地讨论了学生类。如前所述,遵守了所以一行docstring 的编码规范。

多行类docstring

class Student:
    """Student class information.

    This class handle actions performed by a student.
    This class provides information about student full name, age, 
    roll-number and other information.
    Usage:
        import student
        student = student.Student()
        student.get_name()
        >>> 678998
   """
   def __init__(self):
       pass


这个类 docstring 是多行的; 我们写了很多关于 Student 类的用法以及如何使用它。


函数的docstring


函数文档字符串可以写在函数之后,也可以写在函数的顶部。


def is_prime_number(number):
    """Check for prime number.

    Check the given number is prime number 
    or not by checking against all the numbers 
    less the square root of given number.

    :param number:Given number to check for prime
    :type number: int
    :return: True if number is prime otherwise False.
    :rtype: boolean
    """


如果我们使用类型注解对其进一步优化。


def is_prime_number(number: int)->bool:
    """Check for prime number.

    Check the given number is prime number 
    or not by checking against all the numbers 
    less the square root of given number.
    """

结语

当然关于 Python 中的规范还有很多很多,建议大家参考 Python 之禅和 Pep8 对代码进行优化,养成编写 Pythonic 代码的良好习惯。


原文地址:

https://mp.weixin.qq.com/s/fPpZlHS4tBDB3Y_bKaKoBg


(*本文仅代表作者观点,转载请联系原作者)


精彩推荐


    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存