【转】How to type pythonic codes

发布时间 2023-12-06 17:20:24作者: 木屐呀

谈到规范首先想到就是 Python 有名的 PEP8 代码规范文档,它定义了编写 Pythonic 代码的最佳实践。可以在  上查看。但是真正去仔细研究学习这些规范的朋友并不是很多,对此呢这篇文章摘选一些比较常用的代码整洁和规范的技巧和方法,下面让我们一起来学习吧!

命名

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

变量和函数

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

变量的声明

1 names = "python" #变量名
2 namejob_title = "Software Engineer" #带有下划线的变量名
3 populated_countries_list = [] #带有下划线的变量名

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

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

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

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

函数的声明

1 def get_data():
2     pass
3 def calculate_tax_data():
4     pass

函数的声明和变量一样也是通过小写字母和单下划线进行连接。
当然对于函数私有化也是和声明变量类似。

1 def _get_data():
2     pass

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

1 def __path():
2     pass

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

函数名规范

 1 # Wrong Way
 2 def get_user_info(id):
 3     db = get_db_connection()
 4     user = execute_query_for_user(id)
 5     return user
 6 # Right Way
 7 def get_user_by(user_id):
 8     db = get_db_connection()
 9     user = execute_query_for_user(user_id)
10     return user

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

作为开发人员,你有责任在命名变量和函数时仔细考虑,要写让人能够清晰易懂的代码。
当然也方便自己以后去维护。

类的命名规范

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

1 class UserInformation:
2     def get_user(id):
3         db = get_db_connection()
4         user = execute_query_for_user(id)
5         return user

常量的命名规范

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

1 TOTAL = 56
2 TIMEOUT = 6
3 MAX_OVERFLOW = 7

函数和方法的参数

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

1 def calculate_tax(amount, yearly_tax):
2     pass
3 class Player:
4     def get_total_score(self, player_name):
5         pass

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

代码中的表达式和语句

1 users = [
2     {"first_name":"Helen", "age":39},
3     {"first_name":"Buck", "age":10},
4     {"first_name":"anni", "age":29}
5 ]
6 users = sorted(users, key=lambda user: user["first_name"].lower())
7 print(users)

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

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

 1 users = [
 2     {"first_name":"Helen", "age":39},
 3     {"first_name":"Buck", "age":10},
 4     {"first_name":"anni", "age":9}
 5 ]
 6 def get_user_name(user):
 7     """Get name of the user in lower case"""
 8     return user["first_name"].lower()
 9 
10 def get_sorted_dictionary(users):
11     """Sort the nested dictionary"""
12     for user in users:
13         if not isinstance(user, dict):
14             raise ValueError("Not a correct dictionary")
15     if not len(users):
16        raise ValueError("Empty dictionary")
17     users_by_name = sorted(users, key=get_user_name)
18     return users_by_name
19 
20 print(get_sorted_dictionary(users))

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

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

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

将代码分解为函数有助于使复杂的代码变的易于阅读和调试。
这里的代码在 with 语句中执行多项操作。为了提高可读性,您可以将带有 process salary 的代码从 CSV 文件中提取到另一个函数中,以降低出错的可能性。

 1 import csv
 2 with open("employee.csv", mode="r") as csv_file:
 3     csv_reader = csv.DictReader(csv_file)
 4     line_count = 0
 5     process_salary(csv_reader)    
 6  
 7  
 8 def process_salary(csv_reader):
 9 """Process salary of user from csv file."""
10     for row in csv_reader:
11             if line_count == 0:
12                 print(f'Column names are {", ".join(row)}')
13                 line_count += 1
14                 print(f'\t{row["name"]} salary: {row["salary"]}'
15                 f'and was born in {row["birthday month"]}.')
16             line_count += 1
17         print(f'Processed {line_count} lines.')

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

return语句的类型尽量一致

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

1 def calculate_interest(principle, time rate):    
2      if principle > 0:
3          return (principle * time * rate) / 100
4 def calculate_interest(principle, time rate):    
5     if principle < 0:
6         return    
7     return (principle * time * rate) / 100ChaPTER 1  PyThonIC ThInkIng

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

1 def calculate_interest(principle, time rate):    
2      if principle > 0:
3          return (principle * time * rate) / 100
4      else:
5         return None
6 def calculate_interest(principle, time rate):    
7     if principle < 0:
8         return None    
9     return (principle * time * rate) / 100ChaPTER 1  PyThonIC ThInkIng

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

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

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

错误示范

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

正确选择

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

比较布尔值

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

错误示范

1 if is_empty = False
2 if is_empty == False:
3 if is_empty is False:

正确示范

1 is_empty = False
2 if is_empty

使用文档字符串

Docstrings可以在 Python 中声明代码的功能的。通常在方法,类和模块的开头使用。 docstring是该对象的__doc__特殊属性。

Python 官方语言建议使用“”三重双引号“”来编写文档字符串。 你可以在 PEP8 官方文档中找到这些实践。 下面让我们简要介绍一下在 Python 代码中编写 docstrings 的一些最佳实践 。

方法中使用docstring

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

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

    • 即使字符串符合一行,也会使用三重引号。当你想要扩展时,这种注释非常有用。‘
    • 三重引号中的字符串前后不应有任何空行
    • 使用句点(.)结束docstring中的语句
      类似地,可以应用 Python 多行 docstring 规则来编写多行 docstring。在多行上编写文档字符串是用更具描述性的方式记录代码的一种方法。你可以利用 Python 多行文档字符串在 Python 代码中编写描述性文档字符串,而不是在每一行上编写注释。

多行的docstring

 1 def call_weather_api(url, location):
 2     """Get the weather of specific location.
 3  
 4     Calling weather api to check for weather by using weather api and 
 5     location. Make sure you provide city name only, country and county 
 6     names won't be accepted and will throw exception if not found the 
 7     city name.
 8  
 9     :param url:URL of the api to get weather.
10     :type url: str
11     :param location:Location of the city to get the weather.
12     :type location: str
13     :return: Give the weather information of given location.
14     :rtype: str"""

说一下上面代码的注意点

  • 第一行是函数或类的简要描述
  • 每一行语句的末尾有一个句号
  • 文档字符串中的简要描述和摘要之间有一行空白

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

1 def call_weather_api(url: str, location: str) -> str:
2     """Get the weather of specific location.
3  
4     Calling weather api to check for weather by using weather api and 
5     location. Make sure you provide city name only, country and county 
6     names won't be accepted and will throw exception if not found the 
7     city name.
8     """

模块级别的docstring

一般在文件的顶部放置一个模块级的 docstring 来简要描述模块的使用。
这些注释应该放在在导包之前,模块文档字符串应该表明模块的使用方法和功能。
如果觉得在使用模块之前客户端需要明确地知道方法或类,你还可以简要地指定特定方法或类。

 1 """This module contains all of the network related requests. 
 2 This module will check for all the exceptions while making the network 
 3 calls and raise exceptions for any unknown exception.
 4 Make sure that when you use this module,
 5 you handle these exceptions in client code as:
 6 NetworkError exception for network calls.
 7 NetworkNotFound exception if network not found.
 8 """
 9  
10 import urllib3
11 import json

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

  • 对当前模块写一个简要的说明
  • 如果想指定某些对读者有用的模块,如上面的代码,还可以添加异常信息,但是注意不要太详细
1 NetworkError exception for network calls.
2 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

 1 class Student:
 2     """Student class information.
 3  
 4     This class handle actions performed by a student.
 5     This class provides information about student full name, age, 
 6     roll-number and other information.
 7     Usage:
 8         import student
 9         student = student.Student()
10         student.get_name()
11         >>> 678998
12    """
13    def __init__(self):
14        pass

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

函数的docstring

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

 1 ef is_prime_number(number):
 2     """Check for prime number.
 3  
 4     Check the given number is prime number 
 5     or not by checking against all the numbers 
 6     less the square root of given number.
 7  
 8     :param number:Given number to check for prime
 9     :type number: int
10     :return: True if number is prime otherwise False.
11     :rtype: boolean
12     """

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

1 def is_prime_number(number: int)->bool:
2     """Check for prime number.
3  
4     Check the given number is prime number 
5     or not by checking against all the numbers 
6     less the square root of given number.
7     """