Learn how to write idiomatic, effective Python code by leveraging its best features. Python's simplicity quickly lets you become productive with it, but this often means you aren’t using everything the language has to offer. By taking you through Python’s key language features and libraries, this prFluent PythonLuciano ramalhoBeijing. Boston Farnham. Sebastopol. Tokyo OREILLYFluent Pythonby luciano ramalhoCopyright O 2015 Luciano Gama de Sousa Ramalho. All rights reservedPrinted in the United States of americaPublished by Oreilly Media, InC, 1005 Gravenstein Highway North, Sebastopol, CA 95472OReilly books may be purchased for educational,business, or sales promotional use. Online editions arealsoavailableformosttitles(http://safaribooksonline.com).Formoreinformationcontactourcorporateinstitutionalsalesdepartment:800-998-9938orcorporate@oreilly.comEditors: Meghan Blanchette and Rachel Roumeliotis Indexer: Judy McconvilleProduction Editor: Melanie YarbroughCover Designer: Ellie Volckhausen〔 opyeditor: Kim CoferInterior Designer: David FutatoProofreader: Jasmine Kwitynlustrator: Rebecca demarestAugust 2015First editionRevision history for the First Edition:2015-07-24: First release2015-08-21: Second releasehttp://oreilly.com/catalog/errata.csp?isbn=9781491946008forreleasedetailsThe O Reilly logo is a registered trademark of O'Reilly Media, Inc. Fluent Python, the cover image, andrelated trade dress are trademarks of o reilly media, IncWhile the publisher and author have used good faith efforts to ensure that the information and instructionscontained in this work are accurate the publisher and the author disclaim all responsibility for errors oromissions, including without limitation responsibility for damages resulting from the use of or reliance onthis work. Use of the information and instructions contained in this work is at your own risk if any codesamples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with suchlicenses and/or rightsISBN:978-1-491-94600-8Para marta, com todo o meu amorTable of contentsPrefacePart I. PrologueThe python Data Model。春鲁鲁。鲁春A Pythonic Card DeckHow Special Methods Are UsedEmulating Numeric TypesString representationArithmetic Operators12Boolean value of a Custom TypeOverview of Special Methods13Why len is not a method14Chapter Summary14Further Reading15Part l. Data structures2. An Array of Sequences.,,19Overview of Built-In Sequences20List Comprehensions and Generator Expressions21List Comprehensions and readability21Listcomps versus map and filterCartesian Products23Generator Expressions25Tuples Are Not Just Immutable ListsTuples as Records26Tuple unpacking27Nested Tuple Unpacking29d tupleTuples as Immutable Lists32SlicingWhy Slices and Range Exclude the Last Item33Slice objects34Multidimensional Slicing and Ellipsis35Assigning to Slices36sing+ and* with Sequences36Building lists of lists37Augmented assignment with Sequences38a += Assignment puzzler40list sort and the sorted Built-In function42ManagingOrdered Sequences with bisectSearching with bisectInserting with bisect insortWhen a list is not the answer48arrays48Memory views51Num Py and SciP52Deques and other queuesChapter summary57Further Reading593, Dictionaries and SetsGeneric Mapping Types64dict Comprehensions66Overview of Common Mapping MethodsHandling Missing Keys with setdefault68Mappings with Flexible Key lookup70defaultdict: Another Take on Missing KeysThe missing MethodVariations of dictSubclassing UserDictImmutable MappingsSet theory79set literalsSet comprehensions81Set operations82dict and set Under the hoodA Performance Experiment85Hash tables in dictionaries87ⅵi| Table of contentsPractical Consequences of How dict Works90How Sets Work-Practical Consequences93Chapter summary93Further reading944. Text versus Bytes.,97Character issuesByte essentialStructs and memory views102Basic Encoders/decoders103Understanding Encode/ Decode Problems105Coping with UnicodeEncodeError105Coping with UnicodeDecodeerror106Syntax Error When Loading Modules with Unexpected Encoding108How to Discover the Encoding of a byte sequence109BOM: A USeful gremlin110Handling Text Files111Encoding Defaults: A Madhouse114Normalizing Unicode for Saner Comparisons117Case foldinggUtility Functions for Normalized Text Matching120Extreme Normalization: Taking Out Diacritics121Sorting Unicode Text124Sorting with the Unicode Collation Algorithm126The Unicode database127Dual-Mode str and bytes aPis129str Versus bytes in Regular Expressions129str Versus bytes on os Functions130Chapter Summary132Further Reading133Part Il. Functions as objects5. First-Class Functions139Treating a Function Like an object140Higher-Order Functions141Modern Replacements for map, filter, and reduce142Anonymous Functions143The Seven Flavors of Callable Objects144User-Defined Callable Types145Function Introspection146Table of ContentsFrom Positional to Keyword-Only Parameters148Retrieving Information About Parameters150Function annotations154Packages for Functional Programming156The operator Module156Freezing arguments with functools159Chapter summary161Further readins1626. Design patterns with First-Class functions167Case Study: Refactoring Strateg.168Classic strategy168Function-Oriented Strategy172Choosing the Best Strategy: Simple Approach175Finding strategies in a module176Command177Chapter summary179Further readins1807. Function Decorators and closures...................... 183Decorators 101184When Python Executes Decorators185Decorator- Enhanced Strategy Pattern187Variable Scope rules189Closures192The nonlocal declaration195Implementing a Simple Decorator196How It Works198Decorators in the Standard Library199Memoization with functools. Iru cache200Generic Functions with Single Dispatch202Stacked Decorators205Parameterized decorators206A Parameterized Registration Decorator206The Parameterized Clock Decorator209Chapter Summary211Further readins212I Table of Contents