Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo
Effective Python: 59 Specific Ways to Write Better Python

Book Description

It’s easy to start coding with Python, which is why the language is so popular. However, Python’s unique strengths, charms, and expressiveness can be hard to grasp, and there are hidden pitfalls that can easily trip you up.

Effective Python will help you master a truly “Pythonic” approach to programming, harnessing Python’s full power to write exceptionally robust and well-performing code. Using a concise, scenario-driven style, Brett Slatkin brings together 59 Python best practices, tips, and shortcuts, and explains them with realistic code examples.

Drawing on years of experience building Python infrastructure at Google, Slatkin uncovers little-known quirks and idioms that powerfully impact code behavior and performance. You’ll learn the best way to accomplish key tasks, so you can write code that’s easier to understand, maintain, and improve.

Key features include

  • Actionable guidelines for all major areas of Python 3.x and 2.x development, with detailed explanations and examples

  • Best practices for writing functions that clarify intention, promote reuse, and avoid bugs

  • Coverage of how to accurately express behaviors with classes and objects

  • Guidance on how to avoid pitfalls with metaclasses and dynamic attributes

  • More efficient approaches to concurrency and parallelism

  • Better techniques and idioms for using Python’s built-in modules

  • Tools and best practices for collaborative development

  • Solutions for debugging, testing, and optimization in order to improve quality and performance

  • Table of Contents

    1. About This eBook
    2. Title Page
    3. Copyright Page
    4. Praise for Effective Python
    5. Dedication Page
    6. Contents
    7. Preface
      1. What This Book Covers
      2. Conventions Used in This Book
      3. Where to Get the Code and Errata
    8. Acknowledgments
    9. About the Author
    10. 1. Pythonic Thinking
      1. Item 1: Know Which Version of Python You’re Using
      2. Item 2: Follow the PEP 8 Style Guide
      3. Item 3: Know the Differences Between bytes, str, and unicode
      4. Item 4: Write Helper Functions Instead of Complex Expressions
      5. Item 5: Know How to Slice Sequences
      6. Item 6: Avoid Using start, end, and stride in a Single Slice
      7. Item 7: Use List Comprehensions Instead of map and filter
      8. Item 8: Avoid More Than Two Expressions in List Comprehensions
      9. Item 9: Consider Generator Expressions for Large Comprehensions
      10. Item 10: Prefer enumerate Over range
      11. Item 11: Use zip to Process Iterators in Parallel
      12. Item 12: Avoid else Blocks After for and while Loops
      13. Item 13: Take Advantage of Each Block in try/except/else/finally
    11. 2. Functions
      1. Item 14: Prefer Exceptions to Returning None
      2. Item 15: Know How Closures Interact with Variable Scope
      3. Item 16: Consider Generators Instead of Returning Lists
      4. Item 17: Be Defensive When Iterating Over Arguments
      5. Item 18: Reduce Visual Noise with Variable Positional Arguments
      6. Item 19: Provide Optional Behavior with Keyword Arguments
      7. Item 20: Use None and Docstrings to Specify Dynamic Default Arguments
      8. Item 21: Enforce Clarity with Keyword-Only Arguments
    12. 3. Classes and Inheritance
      1. Item 22: Prefer Helper Classes Over Bookkeeping with Dictionaries and Tuples
      2. Item 23: Accept Functions for Simple Interfaces Instead of Classes
      3. Item 24: Use @classmethod Polymorphism to Construct Objects Generically
      4. Item 25: Initialize Parent Classes with super
      5. Item 26: Use Multiple Inheritance Only for Mix-in Utility Classes
      6. Item 27: Prefer Public Attributes Over Private Ones
      7. Item 28: Inherit from for Custom Container Types
    13. 4. Metaclasses and Attributes
      1. Item 29: Use Plain Attributes Instead of Get and Set Methods
      2. Item 30: Consider @property Instead of Refactoring Attributes
      3. Item 31: Use Descriptors for Reusable @property Methods
      4. Item 32: Use __getattr__, __getattribute__, and __setattr__ for Lazy Attributes
      5. Item 33: Validate Subclasses with Metaclasses
      6. Item 34: Register Class Existence with Metaclasses
      7. Item 35: Annotate Class Attributes with Metaclasses
    14. 5. Concurrency and Parallelism
      1. Item 36: Use subprocess to Manage Child Processes
      2. Item 37: Use Threads for Blocking I/O, Avoid for Parallelism
      3. Item 38: Use Lock to Prevent Data Races in Threads
      4. Item 39: Use Queue to Coordinate Work Between Threads
      5. Item 40: Consider Coroutines to Run Many Functions Concurrently
      6. Item 41: Consider concurrent.futures for True Parallelism
    15. 6. Built-in Modules
      1. Item 42: Define Function Decorators with functools.wraps
      2. Item 43: Consider contextlib and with Statements for Reusable try/finally Behavior
      3. Item 44: Make pickle Reliable with copyreg
      4. Item 45: Use datetime Instead of time for Local Clocks
      5. Item 46: Use Built-in Algorithms and Data Structures
      6. Item 47: Use decimal When Precision Is Paramount
      7. Item 48: Know Where to Find Community-Built Modules
    16. 7. Collaboration
      1. Item 49: Write Docstrings for Every Function, Class, and Module
      2. Item 50: Use Packages to Organize Modules and Provide Stable APIs
      3. Item 51: Define a Root Exception to Insulate Callers from APIs
      4. Item 52: Know How to Break Circular Dependencies
      5. Item 53: Use Virtual Environments for Isolated and Reproducible Dependencies
    17. 8. Production
      1. Item 54: Consider Module-Scoped Code to Configure Deployment Environments
      2. Item 55: Use repr Strings for Debugging Output
      3. Item 56: Test Everything with unittest
      4. Item 57: Consider Interactive Debugging with pdb
      5. Item 58: Profile Before Optimizing
      6. Item 59: Use tracemalloc to Understand Memory Usage and Leaks
    18. Index
    19. Code Snippets