clean-code-python -编写整洁的代码

 

Table of Contents

  1. Introduction
  2. Variables
  3. Functions
  4. Objects and Data Structures
  5. Classes
    1. S: Single Responsibility Principle (SRP)
    2. O: Open/Closed Principle (OCP)
    3. L: Liskov Substitution Principle (LSP)
    4. I: Interface Segregation Principle (ISP)
    5. D: Dependency Inversion Principle (DIP)
  6. Don't repeat yourself (DRY)

Introduction

Software engineering principles, from Robert C. Martin's book Clean Code, adapted for Python. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in Python.

Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.

Inspired from clean-code-javascript

Targets Python3.7+

Variables

Use meaningful and pronounceable variable names

Bad:

import datetime


ymdstr = datetime.date.today().strftime("%y-%m-%d")

Good:

import datetime


current_date: str = datetime.date.today().strftime("%y-%m-%d")

⬆ back to top

Use the same vocabulary for the same type of variable

Bad: Here we use three different names for the same underlying entity:

def get_user_info(): pass
def get_client_data(): pass
def get_customer_record(): pass

Good: If the entity is the same, you should be consistent in referring to it in your functions:

def get_user_info(): pass
def get_user_data(): pass
def get_user_record(): pass

Even better Python is (also) an object oriented programming language. If it makes sense, package the functions together with the concrete implementation of the entity in your code, as instance attributes, property methods, or methods:

from typing import Union, Dict, Text


class Record:
    pass


class User:
    info : str

    @property
    def data(self) -> Dict[Text, Text]:
        return {}

    def get_record(self) -> Union[Record, None]:
        return Record()

⬆ back to top

Use searchable names

We will read more code than we will ever write. It's important that the code we do write is readable and searchable. By not naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable.

Bad:

import time


# What is the number 86400 for again?
time.sleep(86400)

Good:

import time


# Declare them in the global namespace for the module.
SECONDS_IN_A_DAY = 60 * 60 * 24
time.sleep(SECONDS_IN_A_DAY)

⬆ back to top

Use explanatory variables

Bad:

import re


address = "One Infinite Loop, Cupertino 95014"
city_zip_code_regex = r"^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$"

matches = re.match(city_zip_code_regex, address)
if matches:
    print(f"{matches[1]}: {matches[2]}")

Not bad:

It's better, but we are still heavily dependent on regex.

import re


address = "One Infinite Loop, Cupertino 95014"
city_zip_code_regex = r"^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$"
matches = re.match(city_zip_code_regex, address)

if matches:
    city, zip_code = matches.groups()
    print(f"{city}: {zip_code}")

Good:

Decrease dependence on regex by naming subpatterns.

import re


address = "One Infinite Loop, Cupertino 95014"
city_zip_code_regex = r"^[^,\\]+[,\\\s]+(?P<city>.+?)\s*(?P<zip_code>\d{5})?$"

matches = re.match(city_zip_code_regex, address)
if matches:
    print(f"{matches['city']}, {matches['zip_code']}")

⬆ back to top

Avoid Mental Mapping

Don’t force the reader of your code to translate what the variable means. Explicit is better than implicit.

Bad:

seq = ("Austin", "New York", "San Francisco")

for item in seq:
    #do_stuff()
    #do_some_other_stuff()

    # Wait, what's `item` again?
    print(item)

Good:

locations = ("Austin", "New York", "San Francisco")

for location in locations:
    #do_stuff()
    #do_some_other_stuff()
    # ...
    print(location)

⬆ back to top

Don't add unneeded context

If your class/object name tells you something, don't repeat that in your variable name.

Bad:

class Car:
    car_make: str
    car_model: str
    car_color: str

Good:

class Car:
    make: str
    model: str
    color: str

⬆ back to top

Use default arguments instead of short circuiting or conditionals

Tricky

Why write:

import hashlib


def create_micro_brewery(name):
    name = "Hipster Brew Co." if name is None else name
    slug = hashlib.sha1(name.encode()).hexdigest()
    # etc.

... when you can specify a default argument instead? This also makes it clear that you are expecting a string as the argument.

Good:

from typing import Text
import hashlib


def create_micro_brewery(name: Text = "Hipster Brew Co."):
    slug = hashlib.sha1(name.encode()).hexdigest()
    # etc.

⬆ back to top

Functions

Function arguments (2 or fewer ideally)

Limiting the amount of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.

Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided. Anything more than that should be consolidated. Usually, if you have more th

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apress 2019出版 Python is one of the most popular languages today. Relatively new fields such as data science, AI, robotics, and data analytics, along with traditional professions such as web development and scientific research, are embracing Python. It’s increasingly important for programmers writing code in a dynamic language like Python to make sure that the code is highquality and error-free. As a Python developer, you want to make sure that the software you are building makes your users happy without going over budget or never releasing. Python is a simple language, yet it’s difficult to write great code because there aren’t many resources that teach how to write better Python code. Currently lacking in the Python world are code consistency, patterns, and an understanding of good Pythonic code among developers. For every Python programmer, great Pythonic code has a different meaning. The reason for this could be that Python is being used in so many areas that it’s difficult to reach consensus among developers about specific patterns. In addition, Python doesn’t have any books about clean code like Java and Ruby do. There have been attempts to write those kinds of books to bring clarity to good Python practices, but those attempts have been few and far between, and quickly frankly, they haven’t been high-quality. The main goal of this book is to provide tips to Python developers of various levels so they can write better Python software and programs. This book gives you various techniques irrespective of the field you use Python in. This book covers all levels of Python, from basic to advanced, and shows you how to make your code more Pythonic. Remember, writing software is not only science but art, and this book will teach you how to become a better Python programmer.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值