《Effective Python》小记

Effective Python 59 SPECIFIC WAYS TO WRITE BETTER PYTHON 这本书终于读完了。从这本书里学到不少经验,以及之前忽略的知识。书中部分内容也是库的内容(这么说有失公允,大部分属都会有抄库文档的嫌疑的,因为文档包含了最多的信息),也有很多内容基本上是常识,比如七八章合作和产品的东西。这些内容,看了书也不会,不看书实践一下不会也得会。是“纸上得来终觉浅”的东西。

下面按照目录记一下有用的东西。划掉的是垃圾,加粗或者颜色的是干货。

Chapter 1: Pythonic Thinking
Item 1: Know Which Version of Python You’re Using
Item 2: Follow the PEP 8 Style Guide
Item 3: Know the Differences Between bytes, str, and unicode
Item 4: Write Helper Functions Instead of Complex Expressions
Item 5: Know How to Slice Sequences
Item 6: Avoid Using start, end, and stride in a Single Slice
Item 7: Use List Comprehensions Instead of map and filter
Item 8: Avoid More Than Two Expressions in List Comprehensions
Item 9: Consider Generator Expressions for Large Comprehensions
Item 10: Prefer enumerate Over range
Item 11: Use zip to Process Iterators in Parallel
Item 12: Avoid else Blocks After for and while Loops
Item 13: Take Advantage of Each Block in try/except/else/finally

第一张虽然是Pythonic Thinking,却提出了很多不提倡使用的Python特性。但是我觉得书中这些条条框框没有必要必须遵守。比如6,为了可读性不要在一个切片操作上用3个数字,以及12,避免使用while-else,也是为了可读性。但是我认为,用了也不一定破坏了可读性。但是初衷是好的。我觉得只要不是写的太复杂,能保持一眼看明白或者多看一眼也能看明白,甚至看三眼也看不明白但是看看注释能看明白,也是可以的。本章中我觉得3和4非常有价值,4可以极大提高可读性。从这里我们知道不一定是非要为了重用才将代码封装成函数,为了可读性进行封装也可以。毕竟,函数的名字比注释要“优雅”的多。

Chapter 2: Functions
Item 14: Prefer Exceptions to Returning None
Item 15: Know How Closures Interact with Variable Scope
Item 16: Consider Generators Instead of Returning Lists
Item 17: Be Defensive When Iterating Over Arguments
Item 18: Reduce Visual Noise with Variable Positional Arguments
Item 19: Provide Optional Behavior with Keyword Arguments
Item 20: Use None and Docstrings to Specify Dynamic Default Arguments
Item 21: Enforce Clarity with Keyword-Only Arguments

14,15,16是干货,抛出一个有时候我们希望错误打断函数运行(如果出错之后后面的代码没有价值了的话),这样更好调试。对于调用出也可以使用try-except处理,而不是罗列一些if-else。有关闭包是一个重点知识。以及迭代器,不过这里感觉也并不是太深入。有关yield我还得多花点时间研究下。后面几条基本上是为了可维护性做的一些惯例。

Chapter 3: Classes and Inheritance
Item 22: Prefer Helper Classes Over Bookkeeping with Dictionaries and Tuples
Item 23: Accept Functions for Simple Interfaces Instead of Classes
Item 24: Use @classmethod Polymorphism to Construct Objects Generically
Item 25: Initialize Parent Classes with super
Item 26: Use Multiple Inheritance Only for Mix-in Utility Classes
Item 27: Prefer Public Attributes Over Private Ones
Item 28: Inherit from collections.abc for Custom Container Types

本章是面向对象的内容。Python很好入门,但是很多人将他当做一门面向过程的语言,项目都用函数组织。其实Python是纯正的面向对象的语言。就连函数也是一等的object。目前我们公司的项目都是以函数的形式组织的,我觉得很多地方都可以使用class,重用性会更好。

Chapter 4: Metaclasses and Attributes
Item 29: Use Plain Attributes Instead of Get and Set Methods
Item 30: Consider @property Instead of Refactoring Attributes Item 31: Use Descriptors for Reusable @property Methods
Item 32: Use __getattr__, __getattribute__, and __setattr__ for Lazy Attributes
Item 33: Validate Subclasses with Metaclasses
Item 34: Register Class Existence with Metaclasses
Item 35: Annotate Class Attributes with Metaclasses

这一章比较好,主要讲了Python获取属性的过程。这里的内容我觉得大多数和Python有关的书都讲不到。关于获取属性的部分我结合文档写了这篇博客。有关metaclass的部分我总结了这篇博客。都是干货。

Chapter 5: Concurrency and Parallelism
Item 36: Use subprocess to Manage Child Processes
Item 37: Use Threads for Blocking I/O, Avoid for Parallelism
Item 38: Use Lock to Prevent Data Races in Threads
Item 39: Use Queue to Coordinate Work Between Threads
Item 40: Consider Coroutines to Run Many Functions Concurrently
Item 41: Consider concurrent.futures for True Parallelism

这章涉及并行,进程、线程、协程等概念。目前用到的不太多,所以没有深入研究。这部分内容要结合操作系统的知识。以后再深入了解吧。

Chapter 6: Built-in Modules
Item 42: Define Function Decorators with functools.wraps
Item 43: Consider contextlib and with Statements for Reusable try/finally Behavior
Item 44: Make pickle Reliable with copyreg
Item 45: Use datetime Instead of time for Local Clocks
Item 46: Use Built-in Algorithms and Data Structures
Item 47: Use decimal When Precision Is Paramount
Item 48: Know Where to Find Community-Built Modules

Chapter 7: Collaboration
Item 49: Write Docstrings for Every Function, Class, and Module
Item 50: Use Packages to Organize Modules and Provide Stable APIs
Item 51: Define a Root Exception to Insulate Callers from APIs
Item 52: Know How to Break Circular Dependencies
Item 53: Use Virtual Environments for Isolated and Reproducible Dependencies

Chapter 8: Production
Item 54: Consider Module-Scoped Code to Configure Deployment Environments
Item 55: Use repr Strings for Debugging Output Item 56: Test Everything with unittest
Item 57: Consider Interactive Debugging with pdb Item 58: Profile Before Optimizing
Item 59: Use tracemalloc to Understand Memory Usage and Leaks

第六章将build-in函数,不如文档详细。甚至有点过时。

第七八章是开发经验,可以参考一下。不过没有应用的话都是纸上谈兵。

就写这些吧,下一步准备结合源代码和文档研究一下常用的函数、数据结构和库。



Leave a comment

您的电子邮箱地址不会被公开。 必填项已用 * 标注