Table Of Contentptg31999699
Praise for Effective Python
“I have been recommending this book enthusiastically since the first edition
appeared in 2015. This new edition, updated and expanded for Python 3, is a
treasure trove of practical Python programming wisdom that can benefit pro-
grammers of all experience levels.”
—Wes McKinney, Creator of Python Pandas project, Director of Ursa Labs
“If you’re coming from another language, this is your definitive guide to taking
full advantage of the unique features Python has to offer. I’ve been working with
Python for nearly twenty years and I still learned a bunch of useful tricks, espe-
cially around newer features introduced by Python 3. Effective Python is crammed
with actionable advice, and really helps define what our community means when
they talk about Pythonic code.”
—Simon Willison, Co-creator of Django
“I’ve been programming in Python for years and thought I knew it pretty well.
Thanks to this treasure trove of tips and techniques, I’ve discovered many ways
to improve my Python code to make it faster (e.g., using bisect to search sorted
lists), easier to read (e.g., enforcing keyword-only arguments), less prone to error
(e.g., unpacking with starred expressions), and more Pythonic (e.g., using zip to
iterate over lists in parallel). Plus, the second edition is a great way to quickly get
up to speed on Python 3 features, such as the walrus operator, f-strings, and the
typing module.”
ptg31999699
—Pamela Fox, Creator of Khan Academy programming courses
“Now that Python 3 has finally become the standard version of Python, it’s
already gone through eight minor releases and a lot of new features have been
added throughout. Brett Slatkin returns with a second edition of Effective Python
with a huge new list of Python idioms and straightforward recommendations,
catching up with everything that’s introduced in version 3 all the way through
3.8 that we’ll all want to use as we finally leave Python 2 behind. Early sections
lay out an enormous list of tips regarding new Python 3 syntaxes and concepts
like string and byte objects, f-strings, assignment expressions (and their special
nickname you might not know), and catch-all unpacking of tuples. Later sec-
tions take on bigger subjects, all of which are packed with things I either didn’t
know or which I’m always trying to teach to others, including ‘Metaclasses and
Attributes’ (good advice includes ‘Prefer Class Decorators over Metaclasses’ and
also introduces a new magic method ‘__init_subclass__()’ I wasn’t familiar with),
‘Concurrency’ (favorite advice: ‘Use Threads for Blocking I/O, but not Parallel-
ism,’ but it also covers asyncio and coroutines correctly) and ‘Robustness and
Performance’ (advice given: ‘Profile before Optimizing’). It’s a joy to go through
each section as everything I read is terrific best practice information smartly
stated, and I’m considering quoting from this book in the future as it has such
great advice all throughout. This is the definite winner for the ‘if you only read
one Python book this year...’ contest.
—Mike Bayer, Creator of SQLAlchemy
“This is a great book for both novice and experienced programmers. The code
examples and explanations are well thought out and explained concisely and
thoroughly. The second edition updates the advice for Python 3, and it’s fantastic!
I’ve been using Python for almost 20 years, and I learned something new every
few pages. The advice given in this book will serve anyone well.”
—Titus Brown, Associate Professor at UC Davis
“Once again, Brett Slatkin has managed to condense a wide range of solid prac-
tices from the community into a single volume. From exotic topics like metaclasses
and concurrency to crucial basics like robustness, testing, and collaboration, the
updated Effective Python makes a consensus view of what’s ‘Pythonic’ available to
a wide audience.”
—Brandon Rhodes, Author of python-patterns.guide
ptg31999699
Effective Python
Second Edition
ptg31999699
This page intentionally left blank
ptg31999699
Effective Python
90 SPECIFIC WAYS TO WRITE BETTER PYTHON
Second Edition
ptg31999699
Brett Slatkin
Many of the designations used by manufacturers and sellers to distinguish their Editor-in-Chief
products are claimed as trademarks. Where those designations appear in this Mark L. Taub
book, and the publisher was aware of a trademark claim, the designations have
Executive Editor
been printed with initial capital letters or in all capitals.
Deborah Williams
The author and publisher have taken care in the preparation of this book, but
Development Editor
make no expressed or implied warranty of any kind and assume no responsibility
Chris Zahn
for errors or omissions. No liability is assumed for incidental or consequential
damages in connection with or arising out of the use of the information or Managing Editor
programs contained herein. Sandra Schroeder
For information about buying this title in bulk quantities, or for special Senior Project Editor
sales opportunities (which may include electronic versions; custom cover Lori Lyons
designs; and content particular to your business, training goals, marketing Production Manager
focus, or branding interests), please contact our corporate sales department Aswini Kumar/codeMantra
at corpsales@pearsoned.com or (800) 382-3419.
Copy Editor
For government sales inquiries, please contact governmentsales@pearsoned.com. Catherine D. Wilson
For questions about sales outside the U.S., please contact intlcs@pearson.com. Indexer
Visit us on the Web: informit.com/aw Cheryl Lenser ptg31999699
Library of Congress Control Number: On file Proofreader
Gill Editorial Services
Copyright © 2020 Pearson Education, Inc.
Cover Designer
All rights reserved. This publication is protected by copyright, and permission
Chuti Prasertsith
must be obtained from the publisher prior to any prohibited reproduction, storage
in a retrieval system, or transmission in any form or by any means, electronic, Compositor
mechanical, photocopying, recording, or likewise. For information regarding codeMantra
permissions, request forms and the appropriate contacts within the Pearson
Education Global Rights & Permissions Department, please visit www.pearson.
com/permissions/.
ISBN-13: 978-0-13-485398-7
ISBN-10: 0-13-485398-9
ScoutAutomatedPrintCode
To our family
ptg31999699
This page intentionally left blank
ptg31999699
Contents at a Glance
Preface xvii
Acknowledgments xxi
About the Author xxiii
Chapter 1: Pythonic Thinking 1
Chapter 2: Lists and Dictionaries 43
ptg31999699
Chapter 3: Functions 77
Chapter 4: Comprehensions and Generators 107
Chapter 5: Classes and Interfaces 145
Chapter 6: Metaclasses and Attributes 181
Chapter 7: Concurrency and Parallelism 225
Chapter 8: Robustness and Performance 299
Chapter 9: Testing and Debugging 353
Chapter 10: Collaboration 389
Index 435