Effective Python:编写好Python的90个有效方法(第2版 英文版)

978-7-115-63406-1
作者: (美)布雷特·斯拉特金(Brett Slatkin)
译者:
编辑: 陈灿然
分类: Python

图书目录:

目录

Chapter 1 Pythonic Thinking / 第 1 章 Pythonic 思维 1

Item 1: Know Which Version of Python You’re Using /

条目 1:查询自己使用的 Python 版本 1

Item 2: Follow the PEP 8 Style Guide /

条目 2:遵循 PEP 8 风格指南 2

Item 3: Know the Differences Between bytes and str /

条目 3:了解 bytes 和 str 之间的区别 5

Item 4: Prefer Interpolated F-Strings Over C-style Format Strings and str.format /

条目 4:使用支持插值的 f-string 取代 C 风格的格式化字符串和str.format 11

Item 5: Write Helper Functions Instead of Complex Expressions /

条目 5:使用辅助函数取代复杂表达式 21

Item 6: Prefer Multiple Assignment Unpacking Over Indexing /

条目 6:把数据结构直接拆分到多个变量里,避免通过下标访问 24

Item 7: Prefer enumerate Over range /

条目 7:尽量用 enumerate 取代 range 28

Item 8: Use zip to Process Iterators in Parallel /

条目 8:使用 zip 并行处理迭代器 30

Item 9: Avoid else Blocks After for and while Loops /

条目 9:避免在 for 和 while 循环后使用 else 块 32

Item 10: Prevent Repetition with Assignment Expressions /

条目 10:使用赋值表达式减少重复代码 35

Chapter 2 Lists and Dictionaries / 第 2 章 列表和字典 43

Item 11: Know How to Slice Sequences /

条目 11:学会对序列做切片 43

Item 12: Avoid Striding and Slicing in a Single Expression /

条目 12:避免在切片里同时指定起止下标和步进 46

Item 13: Prefer Catch-All Unpacking Over Slicing /

条目 13:通过带星号的 unpacking 操作来捕获多个元素,避免用切片 48

Item 14: Sort by Complex Criteria Using the key Parameter /

条目 14:使用 sort 方法的 key 参数表示复杂的排序逻辑 52

Item 15: Be Cautious When Relying on dict Insertion Ordering /

条目 15:不要过分依赖给 dict 添加条目时所用的顺序 58

Item 16: Prefer get Over in and KeyError to Handle Missing Dictionary Keys /

条目 16:使用 get 处理键不在字典中的情况,避免使用 in 与 KeyError 65

Item 17: Prefer defaultdict Over setdefault to Handle Missing Items in Internal State /

条目 17:使用 defaultdict 处理内部状态中缺失的元素,而避免使用setdefault 70

Item 18: Know How to Construct Key-Dependent Default Values with __missing__ /

条目 18:学会使用__missing__构建依赖键的默认值 73

Chapter 3 Functions / 第 3 章 函数 77

Item 19: Never Unpack More Than Three Variables When Functions Retur Multiple Values /

条目 19:避免把函数返回的多个数值拆分到 3 个以上的变量中 77

Item 20: Prefer Raising Exceptions to Returning None /

条目 20:遇到意外状况时应该抛出异常,而不是返回 None 80

Item 21: Know How Closures Interact with Variable Scope /

条目 21:了解如何在闭包里面使用外围作用域中的变量 83

Item 22: Reduce Visual Noise with Variable Positional Arguments /

条目 22:使用数量可变的位置参数给函数设计清晰的参数列表 87

Item 23: Provide Optional Behavior with Keyword Arguments /

条目 23:使用关键字参数表示可选行为 90

Item 24: Use None and Docstrings to Specify Dynamic Default Arguments /

条目 24:使用 None 和文档字符串描述默认值会变的参数 94

Item 25: Enforce Clarity with Keyword-Only and Positional-Only Arguments /

条目 25:使用只能以关键字指定和只能按位置传入的参数来设计清晰的参数列表 97

Item 26: Define Function Decorators with functools.wraps /

条目 26:使用 functools.wraps 定义函数修饰器 102

Chapter 4 Comprehensions and Generators / 第 4 章 推导和生成器 107

Item 27: Use Comprehensions Instead of map and filter /

条目 27:使用推导取代 map 和 filter 107

Item 28: Avoid More Than Two Control Subexpressions in Comprehensions /

条目 28:在推导中避免超过两个控制子表达式 109

Item 29: Avoid Repeated Work in Comprehensions by Using Assignment Expressions /

条目 29:使用赋值表达式在推导中避免重复代码 111

Item 30: Consider Generators Instead of Returning Lists /

条目 30:考虑使用生成器而不是返回列表 114

Item 31: Be Defensive When Iterating Over Arguments /

条目 31:谨慎地迭代函数所收到的参数 117

Item 32: Consider Generator Expressions for Large List Comprehensions /

条目 32:考虑使用生成器表达式来进行大型列表推导的组合 122

Item 33: Compose Multiple Generators with yield from /

条目 33:使用 yield from 组合多个生成器 124

Item 34: Avoid Injecting Data into Generators with send /

条目 34:避免使用 send 向生成器注入数据 127

Item 35: Avoid Causing State Transitions in Generators with throw /

条目 35:避免通过 throw 变换生成器的状态 133

Item 36: Consider itertools for Working with Iterators and Generators /

条目 36:考虑使用 itertools 处理迭代器和生成器 138

Chapter 5 Classes and Interfaces / 第 5 章 类和接口 145

Item 37: Compose Classes Instead of Nesting Many Levels of Built-in Types /

条目 37:使用组合起来的类来实现多层结构,避免用嵌套的内置类型 145

Item 38: Accept Functions Instead of Classes for Simple Interfaces /

条目 38:接受函数而不是类来实现简单接口 152

Item 39: Use @classmethod Polymorphism to Construct Objects Generically /

条目 39:通过@classmethod 多态来构建同一体系中的各类对象 155

Item 40: Initialize Parent Classes with super /

条目 40:使用 super 初始化超类 160

Item 41: Consider Composing Functionality with Mix-in Classes /

条目 41:考虑使用混合类来组合功能 165

Item 42: Prefer Public Attributes Over Private Ones /

条目 42:优先考虑使用共有属性表示应受保护的数据,避免使用私有属性表示 170

Item 43: Inherit from collections.abc for Custom Container Types /

条目 43:使用 collections.abc 继承自定义容器类型 175

Chapter 6 Metaclasses and Attributes / 第 6 章 元类和属性 181

Item 44: Use Plain Attributes Instead of Setter and Getter Methods /

条目 44:使用纯属性而不是 setter 和 getter 方法 181

Item 45: Consider @property Instead of Refactoring Attributes /

条目 45:考虑使用@property 而不是重构属性 186

Item 46: Use Descriptors for Reusable @property Methods /

条目 46:使用描述符来改写需要复用的@property 方法 190

Item 47: Use __getattr__, __getattribute__, and __setattr__ for Lazy Attributes /

条目 47:使用__getattr__、__getattribute__和__setattr__处理惰性属性 195

Item 48: Validate Subclasses with __init_subclass__ /

条目 48:使用__init_subclass__验证子类 201

Item 49: Register Class Existence with __init_subclass__ /

条目 49:使用__init_subclass__记录现有的子类 208

Item 50: Annotate Class Attributes with __set_name__ /

条目 50:使用__set_name__注释类属性 214

Item 51: Prefer Class Decorators Over Metaclasses for Composable Class Extensions /

条目 51:使用类修饰器而不是元类来实现可组合的类扩展 218

Chapter 7 Concurrency and Parallelism / 第 7 章 并发和并行 225

Item 52: Use subprocess to Manage Child Processes /

条目 52:使用 subprocess 管理子进程 226

Item 53: Use Threads for Blocking I/O, Avoid for Parallelism /

条目 53:使用线程处理阻塞 I/O,但避免使用它做并行计算 230

Item 54: Use Lock to Prevent Data Races in Threads /

条目 54:使用 Lock 避免线程中的数据竞争 235

Item 55: Use Queue to Coordinate Work Between Threads /

条目 55:使用 Queue 协调线程间的工作 238

Item 56: Know How to Recognize When Concurrency Is Necessary /

条目 56:学会判断何时需要并发 248

Item 57: Avoid Creating New Thread Instances for On-demand Fan-out /

条目 57:避免为按需分发创建新的 Thread 实例 252

Item 58: Understand How Using Queue for Concurrency Requires Refactoring /

条目 58:学会正确地重构代码,以便用 Queue 做并发 257

Item 59: Consider ThreadPoolExecutor When Threads Are Necessary for Concurrency /

条目 59:在需要并发时考虑 ThreadPoolExecutor 264

Item 60: Achieve Highly Concurrent I/O with Coroutines /

条目 60:使用协程实现高并发 I/O 266

Item 61: Know How to Port Threaded I/O to asyncio /

条目 61:了解如何将基于线程的 I/O 移植到 asyncio 271

Item 62: Mix Threads and Coroutines to Ease the Transition to asyncio /

条目 62:混合使用线程和协程以便过渡到 asyncio 282

Item 63: Avoid Blocking the asyncio Event Loop to Maximize Responsiveness /

条目 63:避免阻塞 asyncio 事件循环以最大化程序的响应能力 289

Item 64: Consider concurrent.futures for True Parallelism /

条目 64:考虑 concurrent.futures 以实现真正的并行计算 292

Chapter 8 Robustness and Performance / 第 8 章 稳定性和性能 299

Item 65: Take Advantage of Each Block in try/except/else/finally /

条目 65:充分利用 try/except/else/finally 结构中的每个代码块 299

Item 66: Consider contextlib and with Statements for Reusable try/finally Behavior /

条目 66:考虑使用 contextlib 和 with 语句来改写可复用的 try/finally 代码 304

Item 67: Use datetime Instead of time for Local Clocks /

条目 67:使用 datetime 模块而不是 time 模块处理本地时间 308

Item 68: Make pickle Reliable with copyreg /

条目 68:使用 copyreg 实现可靠的 pickle 操作 312

Item 69: Use decimal When Precision Is Paramount /

条目 69:在需要准确计算时使用 decimal 表示相应的数值 319

Item 70: Profile Before Optimizing /

条目 70:在优化之前进行性能分析 322

Item 71: Prefer deque for Producer – Consumer Queues /

条目 71:优先考虑使用 deque 实现生产者-消费者队列 326

Item 72: Consider Searching Sorted Sequences with bisect /

条目 72:考虑使用 bisect 搜索排序序列 334

Item 73: Know How to Use heapq for Priority Queues /

条目 73:学会使用 heapq 制作优先级队列 336

Item 74: Consider memoryview and bytearray for Zero-Copy Interactions with bytes /

条目 74:考虑使用 memoryview 和 bytearray 来实现无须拷贝的 bytes 操作 346

Chapter 9 Testing and Debugging / 第 9 章 测试和调试 353

Item 75: Use repr Strings for Debugging Output /

条目 75:使用 repr 字符串输出调试信息 354

Item 76: Verify Related Behaviors in TestCase Subclasses /

条目 76:通过 TestCase 子类验证相关行为 357

Item 77: Isolate Tests from Each Other with setUp, tearDown, setUpModule, and tearDownModule /

条目 77:使用 setUp、tearDown、setUpModule 和tearDownModule 将测试隔离开 365

Item 78: Use Mocks to Test Code with Complex Dependencies /

条目 78:使用 Mock 来模拟受测代码所依赖的复杂函数 367

Item 79: Encapsulate Dependencies to Facilitate Mocking and Testing /

条目 79:封装依赖关系以便于模拟和测试 375

Item 80: Consider Interactive Debugging with pdb /

条目 80:考虑使用 pdb 进行交互式调试 379

Item 81: Use tracemalloc to Understand Memory Usage and Leaks /

条目 81:使用 tracemalloc 了解内存使用和泄漏情况 384

Chapter 10 Collaboration / 第 10 章 协作开发 389

Item 82: Know Where to Find Community-Built Modules /

条目 82:学会寻找由其他 Python 开发者所构建的模块 389

Item 83: Use Virtual Environments for Isolated and Reproducible Dependencies /

条目 83:使用虚拟环境隔离环境,并重建依赖关系 390

Item 84: Write Docstrings for Every Function, Class, and Module /

条目 84:为每个函数、类和模块编写文档字符串 396

Item 85: Use Packages to Organize Modules and Provide Stable APIs /

条目 85:使用包来组织模块并提供稳定的 API 401

Item 86: Consider Module-Scoped Code to Configure Deployment Environments /

条目 86:考虑使用模块级别的代码来配置不同的部署环境 406

Item 87: Define a Root Exception to Insulate Callers from APIs /

条目 87:使用根异常来隔离调用者与 API 408

Item 88: Know How to Break Circular Dependencies /

条目 88:了解如何打破循环依赖关系 413

Item 89: Consider warnings to Refactor and Migrate Usage /

条目 89:考虑使用 warnings 来重构和迁移用法 418

Item 90: Consider Static Analysis via typing to Obviate Bugs /

条目 90:考虑使用 typing 做静态分析来消除错误 425

详情

本书是Effective Python的第2版,基于Python 3进行了全面升级。本书分为10章,包含90个条目,形式简洁、表述准确。每个条目都基于对Python的独到见解,告诉读者如何高效地编写Python程序。与第1版相比,第2版只关注Python 3,而不再兼顾 Python 2。根据Python语言引入的新特性,以及Python开发者所形成的新经验,对第1版中的某些思路与解决方案进行了修订,以更好地发挥Python的优势。本书删除了过时的知识点,并添加了对Python新特性的一些介绍。新版中增加了31个条目,并专门设立了几章来强调列表和字典、推导和生成器、元类和属性、稳定性和性能,以及测试和调试 等重要主题。

图书摘要

相关图书

深度学习的数学——使用Python语言
深度学习的数学——使用Python语言
动手学自然语言处理
动手学自然语言处理
Web应用安全
Web应用安全
Python高性能编程(第2版)
Python高性能编程(第2版)
图像处理与计算机视觉实践——基于OpenCV和Python
图像处理与计算机视觉实践——基于OpenCV和Python
Python数据科学实战
Python数据科学实战

相关文章

相关课程