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 (published by Pearson Addison-Wesley in November, 2024) 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.
Buy the Book on AmazonBuy DRM-free eBook
Visit the GitHub project to see all of the code snippets from the book in one place. Run and modify the example code yourself to confirm your understanding. You can also report any errors you’ve found.
For future updates about the book, related videos, translations, conference presentations, and more, choose one of these ways to stay in touch:
Each chapter in Effective Python contains a broad but related set of items. Each item contains concise and specific guidance explaining how you can write Python programs more effectively. Items include advice on what to do, what to avoid, how to strike the right balance, and why this is the best choice. Items reference each other to make it easier to fill in the gaps as you read. Feel free to jump between items and follow your interest.
This third edition covers the language up through Python version 3.13. This book includes 35 completely new items compared to the second edition, two new chapters focused on robustness and performance, and in-depth coverage of creating C-extension modules and interfacing with native shared libraries. Most of the items from the second edition have been revised and included, but many have undergone substantial updates. For some items, my advice has completely changed (compared to the second edition) due to best practices evolving as Python has matured.
match
for Destructuring in Flow Control; Avoid When if
Statements Are Sufficientbytes
and str
str.format
repr
and str
when Printing Objectsenumerate
over range
zip
to Process Iterators in Parallelelse
Blocks After for
and while
Loopsfor
Loop Variables After the Loop Endsany
and all
for Efficient Short-Circuiting Logicitertools
for Working with Iterators and Generatorsget
over in
and KeyError
to Handle Missing Dictionary Keysdefaultdict
over setdefault
to Handle Missing Items in Internal State__missing__
None
nonlocal
None
and Docstrings to Specify Dynamic Default Argumentsfunctools.wraps
functools.partial
over lambda
Expressions for Glue Functionsmap
and filter
yield from
send
Methodthrow
Methodisinstance
Checksfunctools.singledispatch
for Functional-Style Programming Instead of Object-Oriented Polymorphismdataclasses
for Defining Lightweight Classes@classmethod
Polymorphism to Construct Objects Genericallysuper
dataclasses
for Creating Immutable Objectscollections.abc
Classes for Custom Container Types@property
Instead of Refactoring Attributes@property
Methods__getattr__
, __getattribute__
, and __setattr__
for Lazy Attributes__init_subclass__
__init_subclass__
__set_name__
subprocess
to Manage Child ProcessesLock
to Prevent Data Races in ThreadsQueue
to Coordinate Work Between ThreadsThread
Instances for On-demand Fan-outQueue
for Concurrency Requires RefactoringThreadPoolExecutor
When Threads Are Necessary for Concurrencyasyncio
asyncio
asyncio
Event Loops with async
-friendly Worker Threadsconcurrent.futures
for True Parallelismtry
/ except
/ else
/ finally
assert
Internal Assumptions and raise
Missed Expectationscontextlib
and with
Statements for Reusable try
/ finally
Behaviortry
Blocks as Short as PossibleException
ClassException
and BaseException
traceback
for Enhanced Exception Reporting__debug__
to False
exec
and eval
Unless You’re Building a Developer Tooltimeit
Microbenchmarksctypes
to Rapidly Integrate with Native Librariesmemoryview
and bytearray
for Zero-Copy Interactions with bytes
key
Parametersort
and sorted
bisect
deque
for Producer-Consumer Queuesheapq
for Priority Queuesdatetime
Instead of time
for Local Clocksdecimal
When Precision Is Paramountpickle
Serialization Maintainable with copyreg
TestCase
SubclassessetUp
, tearDown
, setUpModule
, and tearDownModule
assertAlmostEqual
to Control Precision in Floating Point Testspdb
tracemalloc
to Understand Memory Usage and LeaksException
to Insulate Callers from APIswarnings
to Refactor and Migrate Usagetyping
to Obviate Bugszipimport
and zipapp
If, for whatever reason, you’re still primarily using Python 2, despite its end-of-life in April, 2020, the first edition of the book will be more useful to you. For older versions of Python 3, the second edition of this book might be useful.
Effective Python: Third Edition is now available for preorder! Follow this link to buy your copy in advance. It will ship in late November 2024 once the book has finished printing and is stocked in the warehouse. Digital editions will become available when the physical book ships or sooner.