Effective Python: 59 Specific Ways to Write Better Python cover

Effective Python: 59 Specific Ways to Write Better Python

Rating 4.4
Word count
350K words
Chapters
40
Series
Effective Series
ISBN
9787111523550

Tags

Summary

Effective Python is a practice-oriented guide to Python organized by scenarios and items, written by Brett Slatkin, a senior software engineer at Google, and containing 59 items in total. Following the format of Scott Meyers's Effective C++, the author writes each recommendation as "problem scenario—counterexample—revision—explanation of principles," using runnable code snippets to show what to do, what to avoid, and why one approach is better. The book covers the main layers of the Python language: Chapter 1 discusses Pythonic thinking, including confirming the version, PEP 8 style, the difference between bytes and str, and sequence slicing; Chapter 2 discusses functions, involving exceptions and return values, nonlocal in closures, rewriting with generators, variable positional arguments, keyword arguments, and dynamic default values; Chapter 3 discusses classes and inheritance, covering helper classes, @classmethod polymorphism, super initialization, mix-ins, public and private attributes, and custom containers with collections.abc; Chapter 4 discusses metaclasses and attributes, involving plain attributes, @property, descriptors, the __getattr__ family, and using metaclasses to validate, register subclasses and annotate attributes; Chapter 5 discusses concurrency and parallelism, including subprocess, threads and Lock, Queue, coroutines, and concurrent.futures; later chapters also address built-in modules, collaborative development, and debugging, testing and optimization. Because the book was written around 2015, it accommodates the mainstream usage of both Python 3.x and Python 2.x, and some items still contain Python 2 syntax such as print statements and old-style classes, which readers can understand in light of the current state of Python 3. The author's years of experience maintaining Python infrastructure at Google is one of the book's most valuable aspects: it reveals many easily overlooked language details, such as mixing slicing with strides, the timing of closure variable binding, the underlying mechanism of attribute access, and the applicable boundaries of threads and coroutines. The recommendations in the book are not dogma but a set of criteria for judging how code can be more readable, more maintainable and less error-prone.

Editor's review

很多人学Python的路径是“先跑通,再回头补”,结果是语法很熟、代码却越写越绕。《Effective Python》正好针对这一点,它不教你新语法,而是把“同样能跑的两段代码,为什么一段更好”讲透。59条建议按主题分章编排,每一条都是独立短篇:先给场景,再示范错误写法,然后改写,最后解释语言机制层面的原因。通勤时读两三条,当天就能在项目里用上。 这本书最值得称道的是“来自基础架构一线”的视角。作者在Google长期维护Python基础设施,讨论闭包变量绑定、描述符与元类、线程与协程的适用边界时,能给出教科书不讲的微妙差异与真实坑点。第3、4章尤其适合已经会用类但说不清@property、__getattr__到底在做什么的人;第5章关于GIL、Queue和协程的说明,可以帮读者建立“什么时候该上线程、什么时候该上协程”的判断力。 需要提醒的是,本书初版成于2015年前后,条款兼顾Python 2.x与3.x,部分写法(如print语句、旧式类、unicode)在今天已不复存在。把它当成“思维方式与语言机制”的读物,具体语法以你手上的Python 3版本为准。若你想读覆盖新版特性的内容,可再看第二版《90个有效方法》。

Who it's for

A good fit for

  • 已掌握Python基础语法、能独立写脚本,想进一步提升代码质量的开发者
  • 从其他语言转来、想弄清Python惯用法与语言机制的工程师
  • 准备技术面试、需要系统梳理Python进阶知识点的求职者
  • 带团队的技术负责人,可用作代码评审与内部培训的参考条款

Not a good fit for

  • 完全没有编程经验的零基础读者,书中不讲解变量、循环等入门知识
  • 只想要一份快速上手的Python教程或速查手册的人
  • 需要覆盖Python 3.10以上新特性(如match、类型注解新语法)的读者

Reading tips

  1. 不必从头读到尾,先按兴趣跳读条款,遇到与项目相关的主题再精读并跑通示例代码
  2. 读每条时先自己写一版实现,再对照书中的反例,体会差异出在哪里
  3. 配合官方文档阅读第3、4章,把描述符、元类、__getattr__的机制真正弄懂
  4. 注意书中兼顾Python 2.x的写法,练习时改用当前Python 3,并留意与第二版的差异

About the publisher

China Machine Press China · Founded in 1950

In addition to science and technology and professional publishing, the books in our catalog from China Machine Press also reflect a sustained focus on psychology, computing, management, finance and economics, and social sciences. In psychology, the catalog includes works by C. G. Jung and introductions to analytical psychology, as well as applied topics such as stress and health, and addiction and healing. In computing, it features Structure and Interpretation of Computer Programs (JavaScript Edition). Management and finance titles include Administrative Behavior (4th Edition), The Price of Inequality (Collector's Edition), and This Time Is Different: Eight Centuries of Financial Folly (Commemorative Edition). In the philosophy and history of science, there is The Worldview: The Third Edition. Relevant authors include C. G. Jung, William McGuire, Sonu Shamdasani, and Gabor Maté. Public information is limited; the above summarizes the publisher's profile based solely on the books in our catalog.

Contents

  1. Praise for the Book
  2. Translator's Preface
  3. Foreword
  4. Acknowledgments
  5. Chapter 1: Think in Pythonic Ways
  6. Item 1: Confirm the Python Version You Are Using
  7. Item 2: Follow the PEP 8 Style Guide
  8. Item 3: Know the Differences Between bytes, str and unicode
  9. Item 4: Use Helper Functions Instead of Complex Expressions
  10. Item 5: Know How to Slice Sequences
  11. Item 6: Avoid Specifying start, end and stride Together in a Single Slice
  12. Item 7: Use List Comprehensions Instead of map and filter
  13. Item 8: Avoid List Comprehensions with More Than Two Expressions
  14. Item 9: Use Generator Expressions to Rewrite List Comprehensions on Large Data
  15. Item 10: Prefer enumerate to range
  16. Item 11: Use zip to Iterate Two Iterators at Once
  17. Item 12: Avoid else Blocks After for and while Loops
  18. Item 13: Use Each Block in try/except/else/finally Wisely
  19. Chapter 2: Functions
  20. Item 14: Prefer Exceptions to Returning None for Special Cases
  21. Item 15: Know How to Use Variables from the Enclosing Scope in Closures
  22. Item 16: Consider Generators Instead of Functions That Return Lists Directly
  23. Item 17: Be Careful When Iterating Over Arguments
  24. Item 18: Use Variable Positional Arguments to Reduce Visual Noise
  25. Item 19: Use Keyword Arguments to Express Optional Behavior
  26. Item 20: Use None and Docstrings to Describe Parameters with Dynamic Default Values
  27. Item 21: Use Keyword-Only Arguments to Ensure Clarity
  28. Chapter 3: Classes and Inheritance
  29. Item 22: Prefer Helper Classes to Dictionaries and Tuples for Maintaining Program State
  30. Item 23: Simple Interfaces Should Accept Functions, Not Instances of Classes
  31. Item 24: Use @classmethod Polymorphism to Construct Objects Generically
  32. Item 25: Initialize Parent Classes with super
  33. Item 26: Use Multiple Inheritance Only for Mix-in Utility Classes
  34. Item 27: Prefer Public Attributes to Private Attributes
  35. Item 28: Inherit from collections.abc to Implement Custom Container Types
  36. Chapter 4: Metaclasses and Attributes
  37. Item 29: Use Plain Attributes Instead of Get and Set Methods
  38. Item 30: Consider @property Instead of Refactoring Attributes
  39. Item 31: Use Descriptors to Rewrite Reusable @property Methods
  40. Item 32: Use __getattr__, __getattribute__ and __setattr__ to Implement Attributes Generated on Demand

FAQ

这本书和《Effective Python》第二版有什么区别?
本书是第一版中文版,共59条,出版于2016年,兼顾Python 2.x与3.x;第二版中文版为《编写高质量Python代码的90个有效方法》,2021年由机械工业出版社出版,全面基于Python 3,条目增至90条并新增列表与字典、推导与生成器等章节。
零基础可以直接读这本书吗?
不建议。本书默认读者已会写Python代码,重点是写法优劣与语言机制,不讲解基础语法。零基础读者宜先完成一本入门教程,再回来读本书的进阶条款。
书中的代码在现在的Python版本上还能运行吗?
大部分核心示例仍可运行,但书中因兼顾Python 2.x而出现print语句、旧式类、unicode等写法,在Python 3中需相应改写。建议阅读时以语言机制和思路为主,具体语法按当前Python 3版本调整。
59条建议需要全部背下来吗?
不必。这些条款是判断标准而非教条,重点理解“为什么这样写更好”。日常最常用的是切片、闭包、参数设计、属性与并发几类,建议先把这几章吃透,其余按需查阅。

Comments

Find this book

This site is an index: you start “Search all sources” in your browser, and the entries it lists all point to third-party sites; please judge their availability yourself.

More by the same author

Top rated in the same category