logo资料库

Python Tricks A Buffet of Awesome Python Features.pdf

第1页 / 共299页
第2页 / 共299页
第3页 / 共299页
第4页 / 共299页
第5页 / 共299页
第6页 / 共299页
第7页 / 共299页
第8页 / 共299页
资料共299页,剩余部分请下载后查看
Contents
Foreword
Introduction
What's a Python Trick?
What This Book Will Do for You
How to Read This Book
Patterns for Cleaner Python
Covering Your A** With Assertions
Complacent Comma Placement
Context Managers and the with Statement
Underscores, Dunders, and More
A Shocking Truth About String Formatting
The Zen of Python Easter Egg
Effective Functions
Python's Functions Are First-Class
Lambdas Are Single-Expression Functions
The Power of Decorators
Fun With *args and **kwargs
Function Argument Unpacking
Nothing to Return Here
Classes & OOP
Object Comparisons: is vs ==
String Conversion (Every Class Needs a __repr__)
Defining Your Own Exception Classes
Cloning Objects for Fun and Profit
Abstract Base Classes Keep Inheritance in Check
What Namedtuples Are Good For
Class vs Instance Variable Pitfalls
Instance, Class, and Static Methods Demystified
Common Data Structures in Python
Dictionaries, Maps, and Hashtables
Array Data Structures
Records, Structs, and Data Transfer Objects
Sets and Multisets
Stacks (LIFOs)
Queues (FIFOs)
Priority Queues
Looping & Iteration
Writing Pythonic Loops
Comprehending Comprehensions
List Slicing Tricks and the Sushi Operator
Beautiful Iterators
Generators Are Simplified Iterators
Generator Expressions
Iterator Chains
Dictionary Tricks
Dictionary Default Values
Sorting Dictionaries for Fun and Profit
Emulating Switch/Case Statements With Dicts
The Craziest Dict Expression in the West
So Many Ways to Merge Dictionaries
Dictionary Pretty-Printing
Pythonic Productivity Techniques
Exploring Python Modules and Objects
Isolating Project Dependencies With Virtualenv
Peeking Behind the Bytecode Curtain
Closing Thoughts
Free Weekly Tips for Python Developers
PythonistaCafe: A Community for Python Developers
Python Tricks: The Book Dan Bader
For online information and ordering of this and other books by Dan Bader, please visit dbader.org. For more information, please contact Dan Bader at mail@dbader.org. Copyright © Dan Bader (dbader.org), 2016–2017 ISBN: 9781775093305 (paperback) ISBN: 9781775093312 (electronic) Cover design by Anja Pircher Design (anjapircher.com) “Python” and the Python logos are trademarks or registered trade- marks of the Python Software Foundation, used by Dan Bader with permission from the Foundation. Thank you for downloading this ebook. This ebook is licensed for your personal enjoyment only. This ebook may not be re-sold or given away to other people. If you would like to share this book with another per- son, please purchase an additional copy for each recipient. If you’re reading this book and did not purchase it, or it was not purchased for your use only, then please return to dbader.org/pytricks-book and purchase your own copy. Thank you for respecting the hard work be- hind this book. Updated 2017-10-27 I would like to thank Michael Howitz, Johnathan Willitts, Julian Orbach, Johnny Giorgis, Bob White, Daniel Meyer, Michael Stueben, Smital Desai, Andreas Kreisig, David Perkins, Jay Prakash Singh, and Ben Felder for their excellent feedback.
What Pythonistas Say About Python Tricks: The Book ”I love love love the book. It’s like having a seasoned tutor explaining, well, tricks! I’m learning Python on the job and I’m coming from pow- ershell, which I learned on the job—so lots of new, great stuff. When- ever I get stuck in Python (usually with flask blueprints or I feel like my code could be more Pythonic) I post questions in our internal Python chat room. I’m often amazed at some of the answers coworkers give me. Dict com- prehensions, lambdas, and generators often pepper their feedback. I am always impressed and yet flabbergasted at how powerful Python is when you know these tricks and can implement them correctly. Your book was exactly what I wanted to help get me from a bewildered powershell scripter to someone who knows how and when to use these Pythonic ‘tricks’ everyone has been talking about. As someone who doesn’t have my degree in CS it’s nice to have the text to explain things that others might have learned when they were clas- sically educated. I am really enjoying the book and am subscribed to the emails as well, which is how I found out about the book.” — Daniel Meyer, Sr. Desktop Administrator at Tesla Inc.
”I first heard about your book from a co-worker who wanted to trick me with your example of how dictionaries are built. I was almost 100% sure about the reason why the end product was a much smaller/simpler dictionary but I must confess that I did not expect the outcome :) He showed me the book via video conferencing and I sort of skimmed through it as he flipped the pages for me, and I was immediately curi- ous to read more. That same afternoon I purchased my own copy and proceeded to read your explanation for the way dictionaries are created in Python and later that day, as I met a different co-worker for coffee, I used the same trick on him :) He then sprung a different question on the same principle, and be- cause of the way you explained things in your book, I was able tonot* guess the result but correctly answer what the outcome would be. That means that you did a great job at explaining things :)* I am not new in Python and some of the concepts in some of the chap- ters are not new to me, but I must say that I do get something out of every chapter so far, so kudos for writing a very nice book and for do- ing a fantastic job at explaining concepts behind the tricks! I’m very much looking forward to the updates and I will certainly let my friends and co-workers know about your book.” — Og Maciel, Python Developer at Red Hat
”I really enjoyed reading Dan’s book. He explains important Python aspects with clear examples (using two twin cats to explain ‘is‘ vs ‘==‘ for example). It is not just code samples, it discusses relevant implementation details comprehensibly. What really matters though is that this book makes you write better Python code! The book is actually responsible for recent new good Python habits I picked up, for example: using custom exceptions and ABC’s (I found Dan’s blog searching for abstract classes.) These new learnings alone are worth the price.” — Bob Belderbos, Engineer at Oracle & Co-Founder of PyBites
Contents Contents Foreword 1 Introduction 1.1 What’s a Python Trick? . . 1.2 What This Book Will Do for You . 1.3 How to Read This Book . . . . . . . . . . . . . . . . . . . . . . . . . 2 Patterns for Cleaner Python Covering Your A** With Assertions . . . 2.1 2.2 Complacent Comma Placement . . 2.3 Context Managers and the with Statement . 2.4 Underscores, Dunders, and More . . 2.5 A Shocking Truth About String Formatting . 2.6 . “The Zen of Python” Easter Egg . . . . . . . . . . . . . . . . . 3 Effective Functions . . Python’s Functions Are First-Class . 3.1 . 3.2 Lambdas Are Single-Expression Functions . . 3.3 The Power of Decorators . . . 3.4 Fun With *args and **kwargs . 3.5 Function Argument Unpacking . . . . 3.6 Nothing to Return Here . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 6 9 11 11 13 14 15 16 25 29 36 48 56 57 58 68 73 86 91 94 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents 4 Classes & OOP . . . . . . . 4.1 Object Comparisons: “is” vs “==” . . 4.2 String Conversion (Every Class Needs a __repr__) 4.3 Defining Your Own Exception Classes . 4.4 Cloning Objects for Fun and Profit . . 4.5 Abstract Base Classes Keep Inheritance in Check . . 4.6 What Namedtuples Are Good For . 4.7 Class vs Instance Variable Pitfalls . . 4.8 Instance, Class, and Static Methods Demystified . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Common Data Structures in Python . 5.1 Dictionaries, Maps, and Hashtables 5.2 Array Data Structures . . . 5.3 Records, Structs, and Data Transfer Objects . 5.4 . . 5.5 . . 5.6 Queues (FIFOs) . 5.7 Priority Queues . . Sets and Multisets . . Stacks (LIFOs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Looping & Iteration . . . . . . . . . 6.1 Writing Pythonic Loops . . . 6.2 Comprehending Comprehensions 6.3 List Slicing Tricks and the Sushi Operator . 6.4 Beautiful Iterators . . . 6.5 Generators Are Simplified Iterators 6.6 Generator Expressions . . . . . 6.7 Iterator Chains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Dictionary Tricks . . . . . . . Sorting Dictionaries for Fun and Profit . . 7.1 Dictionary Default Values . 7.2 . 7.3 Emulating Switch/Case Statements With Dicts . 7.4 The Craziest Dict Expression in the West . . . . 7.5 7.6 Dictionary Pretty-Printing . . . So Many Ways to Merge Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 98 . 101 . 111 . 116 . . 124 . 128 . 136 . 143 153 . 156 . 163 . 173 . 185 . 189 . 195 . 201 205 . 206 . 210 . 214 . 218 . 231 . 239 . 246 250 . 251 . 255 . 259 . 264 . 271 . 274 7
分享到:
收藏