Some basic principles of writing standard Python code

ztenv 2020-11-13 13:03:45
basic principles writing standard python


Python It's one of the most popular languages today . Relatively new fields like data science 、 Artificial intelligence 、 Robots and data analysis , And traditional majors like Web Development and scientific research , All embracing Python. For using Python For programmers who write code in such a dynamic language , It's becoming more and more important to ensure high quality and error free code . As a Python Developer , You want to make sure that the software you're building will satisfy users , It doesn't go over budget or can't be released . Regarding this , Xiaobian has arranged a copy suitable for all Python Learner information :Python Clean code .

Write Pythonic Code

When it comes to norms, the first thing I think of is Python Famous PEP8 Code specification document , It defines writing Pythonic Code best practices . Can be in https://www.python.org/dev/peps/pep-0008/ Check out . A lot of friends don't really study these norms , In this regard, this article selects some of the more commonly used code neat and standardized skills and methods , Let's study together !

name

All programming languages have variables 、 function 、 Naming conventions for classes, etc , In the name of beauty Python Of course, it's better to use naming conventions . Next, for classes 、 function 、 Methods and so on .

Variables and functions
Use lowercase letters to name functions and variables , And separate words with underscores , Improve code readability .

Declaration of variables

names = "Python" # Variable name 
namejob_title = "Software Engineer" # Variable names with an underline 
populated_countries_list = [] # Variable names with an underline 

You should also consider using non Python Built in method name , If you use Python Please use one or two underscores for method names built in ().

_books = {
}# Privatization of variable names 
__dict = []# prevent python Name confusion in built-in Libraries 

How do you choose to use _ still __ Well ?

If you don't want external classes to access the variable , You should use an underline (_) As a prefix to the internal variables of a class . If the private variable name to be defined is Python For example dict Then use (__).

Declaration of functions

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

Function declarations, like variables, are linked by lowercase letters and single underscores .

Of course, privatization of functions is similar to declaring variables .

def _get_data():
pass

Function starts with a single underline , Privatize it . For the use of Pyton Double underline is used to name the function .

def __path():
pass

In addition to following these naming rules , It's important to use clear and easy to understand variable names .

Function name specification

# 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

here , The second function get_user_by Make sure the same parameters are used to pass variables , To provide the right context for the function . The first function get_user_info It's not so unclear , Because parameters id What does it mean? Here we are not sure , It's the user ID, Or the user pays ID Or any other ID? This code may be useful for using your API Other developers of the . To solve this problem , I changed two things in the second function ; I changed the name of the function and the name of the parameter passed , This makes the code more readable .

As a developer , It is your responsibility to think carefully when naming variables and functions , Write code that people can understand clearly .
Of course, it's also convenient for you to maintain in the future .

The naming convention of the class
Class names should be camel case like most other languages .

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

Naming conventions for constants
In general, constants should be defined in uppercase .

TOTAL = 56
TIMOUT = 6
MAX_OVERFLOW = 7

Parameters of functions and methods
Parameter naming of functions and methods should follow the same rules as variable and method names . Because class methods will self As the first keyword parameter . So don't use... In functions self As a keyword as a parameter , To avoid confusion .

def calculate_tax(amount, yearly_tax):
passs
class Player:
def get_total_score(self, player_name):
pass

About naming, I would like to emphasize these , Let's take a look at the problems needed in expressions and statements .

Expressions and statements in code

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())

What's wrong with this code ?

At first glance, it's not easy to understand this code , Especially for new developers , because lambdas Its grammar is very strange , So it's not easy to understand . Although I use lambda It can save money , However , This does not guarantee the correctness and readability of the code . At the same time, this code can not solve the problem of dictionary missing key exception .

Let's rewrite this code with functions , Make the code more readable and correct ; This function will determine the exception , It's much simpler to write .

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

As you can see , This code checks for all possible unexpected values , And it's more readable than the previous single line code . Single line code looks cool and saves lines , But it adds a lot of complexity to the code . But that doesn't mean a single line of code is bad The point raised here is , If your single line of code makes it harder to read , So please avoid using it , Remember that code is not meant to be cool , Especially in the project team .

Let's consider another example , You're trying to read CSV File and calculate CSV The number of lines processed in the file . The following code shows the importance of making code readable , And how naming plays an important role in making code readable .

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.')

Decomposing code into functions helps make complex code easy to read and debug .

The code here is in with Statement to perform multiple operations . To improve readability , You can bring process salary Code from CSV File to another function , To reduce the possibility of making mistakes .

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.')

Is the code easier to understand .

ad locum , Created a helper function , Not in with Write everything in the statement . This gives the reader a clear understanding of the actual function of the function . If you want to handle a particular exception or want to get from CSV Read more data from the file , You can further decompose this function , To follow the principle of single responsibility , A function does one thing . This is very important !

return The types of statements should be as consistent as possible
If you want the function to return a value , Make sure that all execution paths of the function return the value . however , If you expect a function to perform an operation without returning a value , be Python Will implicitly return None As the default value of the function .

Let's start with an example of a mistake :

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

The right demonstration should be like this :

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

Or that sentence to write easy to read code , It's OK to write more code , Readability is very important .

Use isinstance() Method, not type() Compare
When comparing two object types , Please consider using isinstance() instead of type, because isinstance() To determine whether an object is a subclass of another object is true. Consider such a scenario : If the data structure passed is dict Subclasses of , such as orderdict.type() For a particular type of data structure will fail ; However ,isinstance() It can be recognized that it is dict Subclasses of .

Error model :

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

Choose... Correctly :

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

Compare Boolean values
stay Python There are many ways to compare Boolean values in .

Error model :

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

Correct demonstration :

is_empty = False
if is_empty

Use the document string
Docstrings Can be in Python To declare the function of the code in . Usually in the method , Class and module start with .docstring It's the object's __doc__ Special properties .

Python The official language suggests using “” Triple double quotes “” To write a document string . You can PEP8 These practices are found in official documents . Let's give a brief introduction to Python Write... In code docstrings Some of the best practices .

Method used in docstring

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

About docstring How to write the format of , There are many styles , But there are some uniform standards for these styles .

Even if the string matches one line , You'll also use triple quotes . When you want to expand , This kind of annotation is very useful .

There should be no empty lines before and after the string in triple quotation marks

Use a period (.) end docstring The statement in
Allied , Can be applied Python Multiple lines docstring Rules to write multiple lines docstring. Writing document strings on multiple lines is a way to record code in a more descriptive way . You can use Python Multi line document string in Python Code to write descriptive document string , Instead of writing comments on each line .

Many lines 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"""

Let's talk about the code above

The first line is a brief description of the function or class

There is a period at the end of each line of statement

There is a blank line between the brief description and the abstract in the document string

If you use Python3.6 You can use the type annotation on the above docstring And modify the declaration of parameters .

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.
"""

What's more, it's a lot simpler , If you use Python Type annotations in code , You don't need to write parameter information again .

About type annotations (type hint) Please refer to what I wrote before python Final guidelines for type testing –Typing Use

Module level docstring
A module level... Is usually placed at the top of the file docstring To briefly describe the use of the module .

These comments should be placed before the guided package , The module document string should indicate the usage and function of the module .

If you think the client needs to know the method or class clearly before using the module , You can also briefly specify specific methods or classes .

"""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

When writing a document string for a module , Consider doing the following :

Write a brief description of the current module

If you want to specify some modules that are useful to the reader , Like the code above , You can also add exception information , But be careful not to be too detailed .

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

Will module of docstring As a way to provide descriptive information about a module , There is no need to discuss in detail the operation methods of each function or class .

Class level docstring
class docstring It is mainly used to briefly describe the use of classes and their overall objectives . Let's look at some examples , See how to write class document strings .

Single line class docstring

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

This class has a one line docstring, It briefly discusses the student class . As mentioned earlier , Yes, so a line docstring Code specification of .

Multiline class 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

This class docstring It's multi line ; We wrote a lot about Student Class and how to use it .

Functional docstring
The function document string can be written after the function , It can also be written at the top of the function .

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
"""

If we use type annotations to further optimize it .

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.
"""

Conclusion

Of course about Python There are a lot of specifications in , I suggest you refer to Python Zen and Pep8 Optimize the code , Develop writing Pythonic Good habits of code . If you want to write Cleaner Python Code , Recommended reading 《Python Clean code : Write elegant code 》 A Book .
link

The main purpose of this book is for different levels Python Developers provide skills , So that they can write better Python Software and programs . No matter what field you use Python, This book can provide you with a variety of techniques . This book covers all levels from basic to advanced Python knowledge , And shows you how to make the code more consistent with Python Style .

please remember , Writing software is not just a science , And it's an art ,《Python Clean code : Write elegant code 》 A book will teach you how to be a better Python The programmer .

版权声明
本文为[ztenv]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database