Master the art of Python programming with 125 actionable best practices to write more efficient, readable, and maintainable code. Python is a versatile and powerful language, but leveraging its full potential requires more than just knowing the syntax. Effective Python: 125 Specific Ways to Write Better Python, 3rd Edition is your comprehensive guide to mastering Python's unique strengths and avoiding its hidden pitfalls. This updated edition builds on the acclaimed second edition, expanding from 90 to 125 best practices that are essential for writing high-quality Python code. Drawing on years of experience at Google, Brett Slatkin offers clear, concise, and practical advice for both new and experienced Python developers. Each item in the book provides insight into the
"Pythonic" way of programming, helping you understand how to write code that is not only effective but also elegant and maintainable. Whether you're building web applications, analyzing data, writing automation scripts, or training AI models, this book will equip you with the skills to make a significant impact using Python. Key Features of the 3rd Edition: Expanded Content: Now with 125 actionable guidelines, including 35 entirely new items. Updated Best Practices: Reflects the latest features in Python releases up to version 3.13. New Chapters: Additional chapters on how to build robust programs that achieve high performance. Advanced Topics: In-depth coverage of creating C-extension modules and interfacing with native shared libraries. Practical Examples: Realistic code examples that illustrate each best practice.
| Condition | Price | |||
|---|---|---|---|---|
|
New (12 available)
Ships Separately |
$64.08 USD | Add To Cart | Ships separately from Better World Books suppliers | |
|
eBook Obtain a digital book from our friends at eBooks.com.
|
{{ebooksDotComPrice}} {{ebooksDotComCurrency}} | eBooks.com | Digital edition from eBooks.com | |
|
Audio Book Obtain a digital book from our friends at AudiobooksNow.com.
|
{{audioBooksNowPrice}} {{audioBooksNowCurrency}} | AudiobooksNow.com | Digital edition from AudiobooksNow.com |
| Preface | xvii |
| Acknowledgments | xxiii |
| About the Author | xxv |
| Pythonic Thinking | 1 |
| Know Which Version of Python You're Using | 1 |
| Follow the PEP 8 Style Guide | 3 |
| Never Expect Python to Detect Errors at Compile Time | 6 |
| Write Helper Functions Instead of Complex Expressions | 8 |
| Prefer Multiple-Assignment Unpacking over Indexing | 11 |
| Always Surround Single-Element Tuples with Parentheses | 16 |
| Consider Conditional Expressions for Simple Inline Logic | 19 |
| Prevent Repetition with Assignment Expressions | 24 |
| Consider match for Destructuring in Flow Control; Avoid When if Statements Are Sufficient | 30 |
| Strings and Slicing | 41 |
| Know the Differences Between bytes and str | 41 |
| Prefer Interpolated F-Strings over C-Style Format Strings and str.format | 47 |
| Understand the Difference Between repr and str when Printing Objects | 58 |
| Prefer Explicit String Concatenation over Implicit, Especially in Lists | 62 |
| Know How to Slice Sequences | 67 |
| Avoid Striding and Slicing in a Single Expression | 70 |
| Prefer Catch-All Unpacking over Slicing | 72 |
| Loops and Iterators | 77 |
| Prefer enumerate over range | 77 |
| Use zip to Process Iterators in Parallel | 79 |
| Avoid else Blocks After for and while Loops | 82 |
| Never Use for Loop Variables After the Loop Ends | 85 |
| Be Defensive when Iterating over Arguments | 87 |
| Never Modify Containers While Iterating over Them; Use Copies or Caches Instead | 92 |
| Pass Iterators to any and all for Efficient Short-Circuiting Logic | 98 |
| Consider itertools for Working with Iterators and Generators | 102 |
| Dictionaries | 109 |
| Be Cautious when Relying on Dictionary Insertion Ordering | 109 |
| Prefer get over in and KeyError to Handle Missing Dictionary Keys | 117 |
| Prefer defaultdict over setdefault to Handle Missing Items in Internal State | 122 |
| Know How to Construct Key-Dependent Default Values with _missing_ | 124 |
| Compose Classes Instead of Deeply Nesting Dictionaries, Lists, and Tuples | 127 |
| Functions | 135 |
| Know That Function Arguments Can Be Mutated | 135 |
| Return Dedicated Result Objects Instead of Requiring Function Callers to Unpack More Than Three Variables | 138 |
| Prefer Raising Exceptions to Returning None | 142 |
| Know How Closures Interact with Variable Scope and nonlocal | 145 |
| Reduce Visual Noise with Variable Positional Arguments | 150 |
| Provide Optional Behavior with Keyword Arguments | 153 |
| Use None and Docstrings to Specify Dynamic Default Arguments | 157 |
| Enforce Clarity with Keyword-Only and Positional-Only Arguments | 161 |
| Define Function Decorators with functools.wraps | 166 |
| Prefer functools.partial over lambda Expressions for Glue Functions | 169 |
| Comprehensions and Generators | 173 |
| Use Comprehensions Instead of map and filter | 173 |
| Avoid More Than Two Control Subexpressions in Comprehensions | 176 |
| Reduce Repetition in Comprehensions with Assignment Expressions | 178 |
| Consider Generators Instead of Returning Lists | 182 |
| Consider Generator Expressions for Large List Comprehensions | 184 |
| Compose Multiple Generators with yield from | 186 |
| Pass Iterators into Generators as Arguments Instead of Calling the send Method | 188 |
| Manage Iterative State Transitions with a Class Instead of the Generator throw Method | 195 |
| Classes and Interfaces | 201 |
| Accept Functions Instead of Classes for Simple Interfaces | 201 |
| Prefer Object-Oriented Polymorphism over Functions with isinstance Checks | 205 |
| Consider functools.singledispatch for Functional-Style Programming Instead of Object-Oriented Polymorphism | 210 |
| Prefer dataclasses for Defining Lightweight Classes | 217 |
| Use @classmethod Polymorphism to Construct Objects Generically | 230 |
| Initialize Parent Classes with super | 235 |
| Consider Composing Functionality with Mix-in Classes | 240 |
| Prefer Public Attributes over Private Ones | 245 |
| Prefer dataclasses for Creating Immutable Objects | 250 |
| Inherit from collections.abc Classes for Custom Container Types | 260 |
| Metaclasses and Attributes | 265 |
| Use Plain Attributes Instead of Setter and Getter Methods | 265 |
| Consider @property Instead of Refactoring Attributes | 270 |
| Use Descriptors for Reusable @property Methods | 274 |
| Use _getattr_, _getattribute_, and _setattr_ for Lazy Attributes | 279 |
| Validate Subclasses with _init_subclass_ | 285 |
| Register Class Existence with _init_subclass_ | 293 |
| Annotate Class Attributes with _set_name_ | 299 |
| Consider Class Body Definition Order to Establish Relationships Between Attributes | 303 |
| Prefer Class Decorators over Metaclasses for Composable Class Extensions | 310 |
| Concurrency and Parallelism | 319 |
| Use subprocess to Manage Child Processes | 320 |
| Use Threads for Blocking I/O; Avoid for Parallelism | 324 |
| Use Lock to Prevent Data Races in Threads | 330 |
| Use Queue to Coordinate Work Between Threads | 333 |
| Know How to Recognize When Concurrency Is Necessary | 344 |
| Avoid Creating New Thread Instances for On-Demand Fan-out | 349 |
| Understand How Using Queue for Concurrency Requires Refactoring | 353 |
| Consider ThreadPoolExecutor When Threads Are Necessary for Concurrency | 361 |
| Achieve Highly Concurrent I/O with Coroutines | 364 |
| Know How to Port Threaded I/O to asyncio | 368 |
| Mix Threads and Coroutines to Ease the Transition to asyncio | 381 |
| Maximize Responsiveness of asyncio Event Loops with async-Friendly Worker Threads | 389 |
| Consider concurrent.futures for True Parallelism | 393 |
| Robustness | 399 |
| Take Advantage of Each Block in try/except/else/finally | 399 |
| Assert Internal Assumptions and raise Missed Expectations | 404 |
| Consider contextlib and with Statements for Reusable try/finally Behavior | 408 |
| Always Make try Blocks as Short as Possible | 412 |
| Beware of Exception Variables Disappearing | 414 |
| Beware of Catching the Exception Class | 416 |
| Understand the Difference Between Exception and BaseException | 419 |
| Use traceback for Enhanced Exception Reporting | 424 |
| Consider Explicitly Chaining Exceptions to Clarify Tracebacks | 428 |
| Always Pass Resources into Generators and Have Callers Clean Them Up Outside | 436 |
| Never Set _debug_ to False | 442 |
| Avoid exec and eval Unless You're Building a Developer Tool | 445 |
| Performance | 447 |
| Profile Before Optimizing | 448 |
| Optimize Performance-Critical Code Using timeit Microbenchmarks | 453 |
| Know When and How to Replace Python with Another Programming Language | 458 |
| Consider ctypes to Rapidly Integrate with Native Libraries | 462 |
| Consider Extension Modules to Maximize Performance and Ergonomics | 467 |
| Rely on Precompiled Bytecode and File System Caching to Improve Startup Time | 475 |
| Lazy-Load Modules with Dynamic Imports to Reduce Startup Time | 478 |
| Consider memoryview and bytearray for Zero-Copy Interactions with bytes | 485 |
| Data Structures and Algorithms | 493 |
| Sort by Complex Criteria Using the key Parameter | 493 |
| Know the Difference Between sort and sorted | 499 |
| Consider Searching Sorted Sequences with bisect | 501 |
| Prefer deque for Producer-Consumer Queues | 504 |
| Know How to Use heapq for Priority Queues | 509 |
| Use datetime Instead of time for Local Clocks | 519 |
| Use decimal when Precision Is Paramount | 523 |
| Make pickle Serialization Maintainable with copyreg | 526 |
| Testing and Debugging | 533 |
| Verify Related Behaviors in TestCase Subclasses | 533 |
| Prefer Integration Tests over Unit Tests | 541 |
| Isolate Tests from Each Other with setup, tearDown, setUpModule, and tearDownModule | 547 |
| Use Mocks to Test Code with Complex Dependencies | 550 |
| Encapsulate Dependencies to Facilitate Mocking and Testing | 559 |
| Use assertAlmostEqual to Control Precision in Floating Point Tests | 563 |
| Consider Interactive Debugging with pdb | 565 |
| Use tracemalloc to Understand Memory Usage and Leaks | 570 |
| Collaboration | 575 |
| Know Where to Find Community-Built Modules | 575 |
| Use Virtual Environments for Isolated and Reproducible Dependencies | 576 |
| Write Docstrings for Every Function, Class, and Module | 582 |
| Use Packages to Organize Modules and Provide Stable APIs | 588 |
| Consider Module-Scoped Code to Configure Deployment Environments | 593 |
| Define a Root Exception to Insulate Callers from APIs | 595 |
| Know How to Break Circular Dependencies | 600 |
| Consider warnings to Refactor and Migrate Usage | 605 |
| Consider Static Analysis via typing to Obviate Bugs | 613 |
| Prefer Open Source Projects for Bundling Python Programs over zipimport and zipapp | 621 |
| Index | 627 |
| Table of Contents provided by Ingram Syndetics. All Rights Reserved. |
| Find at your local library from our friends at WorldCat | Find Libraries |
Master the art of Python programming with 125 actionable best practices to write more efficient, readable, and maintainable code. Python is a versatile and powerful language, but leveraging its full potential requires more than just knowing the synta ...
Read full overview
Master the art of Python programming with 125 actionable best practices to write more efficient, readable, and maintainable code. Python is a versatile and powerful language, but leveraging its full potential requires more than just knowing the syntax. Effective Python: 125 Specific Ways to Write Better Python, 3rd Edition is your comprehensive guide to mastering Python's unique strengths and avoiding its hidden pitfalls. This updated edition builds on the acclaimed second edition, expanding from 90 to 125 best practices that are essential for writing high-quality Python code. Drawing on years of experience at Google, Brett Slatkin offers clear, concise, and practical advice for both new and experienced Python developers. Each item in the book provides insight into the
"Pythonic" way of programming, helping you understand how to write code that is not only effective but also elegant and maintainable. Whether you're building web applications, analyzing data, writing automation scripts, or training AI models, this book will equip you with the skills to make a significant impact using Python. Key Features of the 3rd Edition: Expanded Content: Now with 125 actionable guidelines, including 35 entirely new items. Updated Best Practices: Reflects the latest features in Python releases up to version 3.13. New Chapters: Additional chapters on how to build robust programs that achieve high performance. Advanced Topics: In-depth coverage of creating C-extension modules and interfacing with native shared libraries. Practical Examples: Realistic code examples that illustrate each best practice.
| Preface | xvii |
| Acknowledgments | xxiii |
| About the Author | xxv |
| Pythonic Thinking | 1 |
| Know Which Version of Python You're Using | 1 |
| Follow the PEP 8 Style Guide | 3 |
| Never Expect Python to Detect Errors at Compile Time | 6 |
| Write Helper Functions Instead of Complex Expressions | 8 |
| Prefer Multiple-Assignment Unpacking over Indexing | 11 |
| Always Surround Single-Element Tuples with Parentheses | 16 |
| Consider Conditional Expressions for Simple Inline Logic | 19 |
| Prevent Repetition with Assignment Expressions | 24 |
| Consider match for Destructuring in Flow Control; Avoid When if Statements Are Sufficient | 30 |
| Strings and Slicing | 41 |
| Know the Differences Between bytes and str | 41 |
| Prefer Interpolated F-Strings over C-Style Format Strings and str.format | 47 |
| Understand the Difference Between repr and str when Printing Objects | 58 |
| Prefer Explicit String Concatenation over Implicit, Especially in Lists | 62 |
| Know How to Slice Sequences | 67 |
| Avoid Striding and Slicing in a Single Expression | 70 |
| Prefer Catch-All Unpacking over Slicing | 72 |
| Loops and Iterators | 77 |
| Prefer enumerate over range | 77 |
| Use zip to Process Iterators in Parallel | 79 |
| Avoid else Blocks After for and while Loops | 82 |
| Never Use for Loop Variables After the Loop Ends | 85 |
| Be Defensive when Iterating over Arguments | 87 |
| Never Modify Containers While Iterating over Them; Use Copies or Caches Instead | 92 |
| Pass Iterators to any and all for Efficient Short-Circuiting Logic | 98 |
| Consider itertools for Working with Iterators and Generators | 102 |
| Dictionaries | 109 |
| Be Cautious when Relying on Dictionary Insertion Ordering | 109 |
| Prefer get over in and KeyError to Handle Missing Dictionary Keys | 117 |
| Prefer defaultdict over setdefault to Handle Missing Items in Internal State | 122 |
| Know How to Construct Key-Dependent Default Values with _missing_ | 124 |
| Compose Classes Instead of Deeply Nesting Dictionaries, Lists, and Tuples | 127 |
| Functions | 135 |
| Know That Function Arguments Can Be Mutated | 135 |
| Return Dedicated Result Objects Instead of Requiring Function Callers to Unpack More Than Three Variables | 138 |
| Prefer Raising Exceptions to Returning None | 142 |
| Know How Closures Interact with Variable Scope and nonlocal | 145 |
| Reduce Visual Noise with Variable Positional Arguments | 150 |
| Provide Optional Behavior with Keyword Arguments | 153 |
| Use None and Docstrings to Specify Dynamic Default Arguments | 157 |
| Enforce Clarity with Keyword-Only and Positional-Only Arguments | 161 |
| Define Function Decorators with functools.wraps | 166 |
| Prefer functools.partial over lambda Expressions for Glue Functions | 169 |
| Comprehensions and Generators | 173 |
| Use Comprehensions Instead of map and filter | 173 |
| Avoid More Than Two Control Subexpressions in Comprehensions | 176 |
| Reduce Repetition in Comprehensions with Assignment Expressions | 178 |
| Consider Generators Instead of Returning Lists | 182 |
| Consider Generator Expressions for Large List Comprehensions | 184 |
| Compose Multiple Generators with yield from | 186 |
| Pass Iterators into Generators as Arguments Instead of Calling the send Method | 188 |
| Manage Iterative State Transitions with a Class Instead of the Generator throw Method | 195 |
| Classes and Interfaces | 201 |
| Accept Functions Instead of Classes for Simple Interfaces | 201 |
| Prefer Object-Oriented Polymorphism over Functions with isinstance Checks | 205 |
| Consider functools.singledispatch for Functional-Style Programming Instead of Object-Oriented Polymorphism | 210 |
| Prefer dataclasses for Defining Lightweight Classes | 217 |
| Use @classmethod Polymorphism to Construct Objects Generically | 230 |
| Initialize Parent Classes with super | 235 |
| Consider Composing Functionality with Mix-in Classes | 240 |
| Prefer Public Attributes over Private Ones | 245 |
| Prefer dataclasses for Creating Immutable Objects | 250 |
| Inherit from collections.abc Classes for Custom Container Types | 260 |
| Metaclasses and Attributes | 265 |
| Use Plain Attributes Instead of Setter and Getter Methods | 265 |
| Consider @property Instead of Refactoring Attributes | 270 |
| Use Descriptors for Reusable @property Methods | 274 |
| Use _getattr_, _getattribute_, and _setattr_ for Lazy Attributes | 279 |
| Validate Subclasses with _init_subclass_ | 285 |
| Register Class Existence with _init_subclass_ | 293 |
| Annotate Class Attributes with _set_name_ | 299 |
| Consider Class Body Definition Order to Establish Relationships Between Attributes | 303 |
| Prefer Class Decorators over Metaclasses for Composable Class Extensions | 310 |
| Concurrency and Parallelism | 319 |
| Use subprocess to Manage Child Processes | 320 |
| Use Threads for Blocking I/O; Avoid for Parallelism | 324 |
| Use Lock to Prevent Data Races in Threads | 330 |
| Use Queue to Coordinate Work Between Threads | 333 |
| Know How to Recognize When Concurrency Is Necessary | 344 |
| Avoid Creating New Thread Instances for On-Demand Fan-out | 349 |
| Understand How Using Queue for Concurrency Requires Refactoring | 353 |
| Consider ThreadPoolExecutor When Threads Are Necessary for Concurrency | 361 |
| Achieve Highly Concurrent I/O with Coroutines | 364 |
| Know How to Port Threaded I/O to asyncio | 368 |
| Mix Threads and Coroutines to Ease the Transition to asyncio | 381 |
| Maximize Responsiveness of asyncio Event Loops with async-Friendly Worker Threads | 389 |
| Consider concurrent.futures for True Parallelism | 393 |
| Robustness | 399 |
| Take Advantage of Each Block in try/except/else/finally | 399 |
| Assert Internal Assumptions and raise Missed Expectations | 404 |
| Consider contextlib and with Statements for Reusable try/finally Behavior | 408 |
| Always Make try Blocks as Short as Possible | 412 |
| Beware of Exception Variables Disappearing | 414 |
| Beware of Catching the Exception Class | 416 |
| Understand the Difference Between Exception and BaseException | 419 |
| Use traceback for Enhanced Exception Reporting | 424 |
| Consider Explicitly Chaining Exceptions to Clarify Tracebacks | 428 |
| Always Pass Resources into Generators and Have Callers Clean Them Up Outside | 436 |
| Never Set _debug_ to False | 442 |
| Avoid exec and eval Unless You're Building a Developer Tool | 445 |
| Performance | 447 |
| Profile Before Optimizing | 448 |
| Optimize Performance-Critical Code Using timeit Microbenchmarks | 453 |
| Know When and How to Replace Python with Another Programming Language | 458 |
| Consider ctypes to Rapidly Integrate with Native Libraries | 462 |
| Consider Extension Modules to Maximize Performance and Ergonomics | 467 |
| Rely on Precompiled Bytecode and File System Caching to Improve Startup Time | 475 |
| Lazy-Load Modules with Dynamic Imports to Reduce Startup Time | 478 |
| Consider memoryview and bytearray for Zero-Copy Interactions with bytes | 485 |
| Data Structures and Algorithms | 493 |
| Sort by Complex Criteria Using the key Parameter | 493 |
| Know the Difference Between sort and sorted | 499 |
| Consider Searching Sorted Sequences with bisect | 501 |
| Prefer deque for Producer-Consumer Queues | 504 |
| Know How to Use heapq for Priority Queues | 509 |
| Use datetime Instead of time for Local Clocks | 519 |
| Use decimal when Precision Is Paramount | 523 |
| Make pickle Serialization Maintainable with copyreg | 526 |
| Testing and Debugging | 533 |
| Verify Related Behaviors in TestCase Subclasses | 533 |
| Prefer Integration Tests over Unit Tests | 541 |
| Isolate Tests from Each Other with setup, tearDown, setUpModule, and tearDownModule | 547 |
| Use Mocks to Test Code with Complex Dependencies | 550 |
| Encapsulate Dependencies to Facilitate Mocking and Testing | 559 |
| Use assertAlmostEqual to Control Precision in Floating Point Tests | 563 |
| Consider Interactive Debugging with pdb | 565 |
| Use tracemalloc to Understand Memory Usage and Leaks | 570 |
| Collaboration | 575 |
| Know Where to Find Community-Built Modules | 575 |
| Use Virtual Environments for Isolated and Reproducible Dependencies | 576 |
| Write Docstrings for Every Function, Class, and Module | 582 |
| Use Packages to Organize Modules and Provide Stable APIs | 588 |
| Consider Module-Scoped Code to Configure Deployment Environments | 593 |
| Define a Root Exception to Insulate Callers from APIs | 595 |
| Know How to Break Circular Dependencies | 600 |
| Consider warnings to Refactor and Migrate Usage | 605 |
| Consider Static Analysis via typing to Obviate Bugs | 613 |
| Prefer Open Source Projects for Bundling Python Programs over zipimport and zipapp | 621 |
| Index | 627 |
| Table of Contents provided by Ingram Syndetics. All Rights Reserved. |
| Condition | Source | Price | |
|---|---|---|---|
|
New (12 available)
Ships Separately |
Ships separately from Better World Books suppliers | $64.08 USD | Add To Cart |
|
eBook Obtain a digital book from our friends at eBooks.com.
|
Digital edition from eBooks.com | {{ebooksDotComPrice}} {{ebooksDotComCurrency}} | eBooks.com |
|
Audio Book Obtain a digital book from our friends at AudiobooksNow.com.
|
|
{{audioBooksNowPrice}} {{audioBooksNowCurrency}} | Audiobook |
*This is a limited preview of the contents of this book and does not directly represent the item available for sale.*
You are now leaving the Better World Books website to complete your transaction. Your eBook download will be facilitated by our friends at eBooks.com. Thank you for your support and for shopping with Better World Books!
You are now leaving the Better World Books website to complete your transaction. Your audio book download will be facilitated by our friends at AudiobooksNow.com. Thank you for your support and for shopping with Better World Books!
You are now leaving the Better World Books website. Thank you for your support and for shopping with Better World Books!