Home > Store

Effective Python: 125 Specific Ways to Write Better Python, 3rd Edition

eBook (Watermarked)

  • Your Price: $44.79
  • List Price: $55.99
  • Estimated Release: Nov 27, 2024
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

Also available in other formats.

Register your product to gain access to bonus material or receive a coupon.

Description

  • Copyright 2025
  • Edition: 3rd
  • eBook (Watermarked)
  • ISBN-10: 0-13-817221-8
  • ISBN-13: 978-0-13-817221-3

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.

Sample Content

Table of Contents

Chapter 1: Pythonic Thinking

     Item 1: Know Which Version of Python Youre Using

     Item 2: Follow the PEP 8 Style Guide

     Item 3: Never Expect Python to Detect Errors at Compile Time

     Item 4: Write Helper Functions Instead of Complex Expressions

     Item 5: Prefer Multiple-Assignment Unpacking Over Indexing

     Item 6: Always Surround Single-Element Tuples with Parentheses

     Item 7: Consider Conditional Expressions for Simple Inline Logic

     Item 8: Prevent Repetition with Assignment Expressions

     Item 9: Consider match for Destructuring in Flow Control; Avoid When if Statements Are Sufficient

Chapter 2: Strings and Slicing

     Item 10: Know the Differences Between bytes and str

     Item 11: Prefer Interpolated F-Strings over C-Style Format Strings and str.format

     Item 12: Understand the Difference Between  repr and str when Printing Objects

     Item 13: Prefer Explicit String Concatenation over Implicit, Especially in Lists

     Item 14: Know How to Slice Sequences

     Item 15: Avoid Striding and Slicing in a Single Expression

     Item 16: Prefer Catch-All Unpacking Over Slicing

Chapter 3: Loops and Iterators

     Item 17: Prefer enumerate over range

     Item 18: Use zip to Process Iterators in Parallel

     Item 19: Avoid else Blocks After for and while Loops

     Item 20: Never Use for Loop Variables After the Loop Ends

     Item 21: Be Defensive when Iterating over Arguments

     Item 22: Never Modify Containers While Iterating over Them; Use Copies or Caches Instead

     Item 23: Pass Iterators to any and all for Efficient Short-Circuiting Logic

     Item 24: Consider itertools for Working with Iterators and Generators

Chapter 4: Dictionaries

     Item 25: Be Cautious when Relying on Dictionary Insertion Ordering

     Item 26: Prefer get over in and KeyError to Handle Missing Dictionary Keys

     Item 27: Prefer defaultdict over setdefault to Handle Missing Items in Internal State

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

     Item 29: Compose Classes Instead of Deeply Nesting Dictionaries, Lists, and Tuples

Chapter 5: Functions

     Item 30: Know That Function Arguments Can Be Mutated

     Item 31: Return Dedicated Result Objects Instead of Requiring Function Callers to Unpack More Than Three Variables

     Item 32: Prefer Raising Exceptions to Returning None

     Item 33: Know How Closures Interact with Variable Scope and nonlocal

     Item 34: Reduce Visual Noise with Variable Positional Arguments

     Item 35: Provide Optional Behavior with Keyword Arguments

     Item 36: Use None and Docstrings to Specify Dynamic Default Arguments

     Item 37: Enforce Clarity with Keyword-Only and Positional-Only Arguments

     Item 38: Define Function Decorators with functools.wraps

     Item 39: Prefer functools.partial over lambda Expressions for Glue Functions

Chapter 6: Comprehensions and Generators

     Item 40: Use Comprehensions Instead of map and filter

     Item 41: Avoid More Than Two Control Subexpressions in Comprehensions

     Item 42: Reduce Repetition in Comprehensions with Assignment Expressions

     Item 43: Consider Generators Instead of Returning Lists

     Item 44: Consider Generator Expressions for Large List Comprehensions

     Item 45: Compose Multiple Generators with yield from

     Item 46: Pass Iterators into Generators as Arguments Instead of Calling the send Method

     Item 47: Manage Iterative State Transitions with a Class Instead of the Generator throw Method

Chapter 7: Classes and Interfaces

     Item 48: Accept Functions Instead of Classes for Simple Interfaces

     Item 49: Prefer Object-Oriented Polymorphism over Functions with isinstance Checks

     Item 50: Consider functools.singledispatch for Functional-Style Programming Instead of Object-Oriented Polymorphism

     Item 51: Prefer dataclasses for Defining Lightweight Classes

     Item 52: Use @classmethod Polymorphism to Construct Objects Generically

     Item 53: Initialize Parent Classes with super

     Item 54: Consider Composing Functionality with Mix-in Classes

     Item 55: Prefer Public Attributes over Private Ones

     Item 56: Prefer dataclasses for Creating Immutable Objects

     Item 57: Inherit from collections.abc Classes for Custom Container Types

Chapter 8: Metaclasses and Attributes

     Item 58: Use Plain Attributes Instead of Setter and Getter Methods

     Item 59: Consider @property Instead of Refactoring Attributes

     Item 60: Use Descriptors for Reusable @property Methods

     Item 61: Use __getattr__, __getattribute__, and __setattr__ for Lazy Attributes

     Item 62: Validate Subclasses with __init_subclass__

     Item 63: Register Class Existence with __init_subclass__

     Item 64: Annotate Class Attributes with __set_name__

     Item 65: Consider Class Body Definition Order to Establish Relationships Between Attributes

     Item 66: Prefer Class Decorators over Metaclasses for Composable Class Extensions

Chapter 9: Concurrency and Parallelism

     Item 67: Use subprocess to Manage Child Processes

     Item 68: Use Threads for Blocking I/O; Avoid for Parallelism

     Item 69: Use Lock to Prevent Data Races in Threads

     Item 70: Use Queue to Coordinate Work Between Threads

     Item 71: Know How to Recognize When Concurrency Is Necessary

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

     Item 73: Understand How Using Queue for Concurrency Requires Refactoring

     Item 74: Consider ThreadPoolExecutor When Threads Are Necessary for Concurrency

     Item 75: Achieve Highly Concurrent I/O with Coroutines

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

     Item 77: Mix Threads and Coroutines to Ease the Transition to asyncio

     Item 78: Maximize Responsiveness of asyncio Event Loops with async-friendly Worker Threads

     Item 79: Consider concurrent.futures for True Parallelism

Chapter 10: Robustness

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

     Item 81: assert Internal Assumptions and raise Missed Expectations

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

     Item 83: Always Make try Blocks as Short as Possible

     Item 84: Beware of Exception Variables Disappearing

     Item 85: Beware of Catching the Exception Class

     Item 86: Understand the Difference Between Exception and BaseException

     Item 87: Use traceback for Enhanced Exception Reporting

     Item 88: Consider Explicitly Chaining Exceptions to Clarify Tracebacks

     Item 89: Always Pass Resources into Generators and Have Callers Clean Them Up Outside

     Item 90: Never Set __debug__ to False

     Item 91: Avoid exec and eval Unless Youre Building a Developer Tool

Chapter 11: Performance

     Item 92: Profile Before Optimizing

     Item 93: Optimize Performance-Critical Code Using timeit Microbenchmarks

     Item 94: Know When and How to Replace Python with Another Programming Language

     Item 95: Consider ctypes to Rapidly Integrate with Native Libraries

     Item 96: Consider Extension Modules to Maximize Performance and Ergonomics

     Item 97: Rely on Precompiled Bytecode and File System Caching to Improve Startup Time

     Item 98: Lazy-Load Modules with Dynamic Imports to Reduce Startup Time

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

Chapter 12: Data Structures & Algorithms

     Item 100: Sort by Complex Criteria Using the key Parameter

     Item 101: Know the Difference Between sort and sorted

     Item 102: Consider Searching Sorted Sequences with bisect

     Item 103: Prefer deque for Producer-Consumer Queues

     Item 104: Know How to Use heapq for Priority Queues

     Item 105: Use datetime Instead of time for Local Clocks

     Item 106: Use decimal When Precision Is Paramount

     Item 107: Make pickle Serialization Maintainable with copyreg

Chapter 13: Testing and Debugging

     Item 108: Verify Related Behaviors in TestCase Subclasses

     Item 109: Prefer Integration Tests over Unit Tests

     Item 110: Isolate Tests From Each Other with setUp, tearDown, setUpModule, and tearDownModule

     Item 111: Use Mocks to Test Code with Complex Dependencies

     Item 112: Encapsulate Dependencies to Facilitate Mocking and Testing

     Item 113: Use assertAlmostEqual to Control Precision in Floating Point Tests

     Item 114: Consider Interactive Debugging with pdb

     Item 115: Use tracemalloc to Understand Memory Usage and Leaks

Chapter 14: Collaboration

     Item 116: Know Where to Find Community-Built Modules

     Item 117: Use Virtual Environments for Isolated and Reproducible Dependencies

     Item 118: Write Docstrings for Every Function, Class, and Module

     Item 119: Use Packages to Organize Modules and Provide Stable APIs

     Item 120: Consider Module-Scoped Code to Configure Deployment Environments

     Item 121: Define a Root Exception to Insulate Callers from APIs

     Item 122: Know How to Break Circular Dependencies

     Item 123: Consider warnings to Refactor and Migrate Usage

     Item 124: Consider Static Analysis via typing to Obviate Bugs

     Item 125: Prefer Open Source Projects for Bundling Python Programs over zipimport and zipapp

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020