Home Page Icon
Home Page
Table of Contents for
II. Data Structures
Close
II. Data Structures
by Luciano Ramalho
Fluent Python, 2nd Edition
Preface
Who This Book Is For
Who This Book Is Not For
How This Book Is Organized
Hands-On Approach
Hardware Used for Timings
Soapbox: My Personal Perspective
Python Jargon
Python Version Covered
Conventions Used in This Book
Using Code Examples
How to Contact Us
Acknowledgments
I. Prologue
1. The Python Data Model
What’s new in this chapter
A Pythonic Card Deck
How Special Methods Are Used
Emulating Numeric Types
String Representation
Arithmetic Operators
Boolean Value of a Custom Type
Collection API
Overview of Special Methods
Why len Is Not a Method
Chapter Summary
Further Reading
II. Data Structures
2. An Array of Sequences
What’s new in this chapter
Overview of Built-In Sequences
List Comprehensions and Generator Expressions
List Comprehensions and Readability
Listcomps Versus map and filter
Cartesian Products
Generator Expressions
Tuples Are Not Just Immutable Lists
Tuples as Records
Unpacking
Nested Tuple Unpacking
Tuples as Immutable Lists
Tuple versus list methods
Slicing
Why Slices and Range Exclude the Last Item
Slice Objects
Multidimensional Slicing and Ellipsis
Assigning to Slices
Using + and * with Sequences
Building Lists of Lists
Augmented Assignment with Sequences
A += Assignment Puzzler
list.sort and the sorted Built-In Function
Managing Ordered Sequences with bisect
Searching with bisect
Inserting with bisect.insort
When a List Is Not the Answer
Arrays
Memory Views
NumPy
Deques and Other Queues
Chapter Summary
Further Reading
3. Dictionaries and Sets
What’s new in this chapter
Standard API of Mapping Types
dict Comprehensions
Overview of Common Mapping Methods
Handling Missing Keys with setdefault
Mappings with Flexible Key Lookup
defaultdict: Another Take on Missing Keys
The __missing__ Method
Variations of dict
Building custom mappings
Subclassing UserDict
Immutable Mappings
Dictionary views
Set Theory
Set Literals
Set Comprehensions
Set Operations
Set operations on dict views
Internals of sets and dicts
A Performance Experiment
Set hash tables under the hood
The hash table algorithm
Hash table usage in dict
Key-sharing dictionary
Practical Consequences of How dict Works
Chapter Summary
Further Reading
4. Text versus Bytes
What’s new in this chapter
Character Issues
Byte Essentials
Basic Encoders/Decoders
Understanding Encode/Decode Problems
Coping with UnicodeEncodeError
Coping with UnicodeDecodeError
SyntaxError When Loading Modules with Unexpected Encoding
How to Discover the Encoding of a Byte Sequence
BOM: A Useful Gremlin
Handling Text Files
Beware of Encoding Defaults
Normalizing Unicode for Reliable Comparisons
Case Folding
Utility Functions for Normalized Text Matching
Extreme “Normalization”: Taking Out Diacritics
Sorting Unicode Text
Sorting with the Unicode Collation Algorithm
The Unicode Database
Finding characters by name
Numeric meaning of characters
Dual-Mode str and bytes APIs
str Versus bytes in Regular Expressions
str Versus bytes in os Functions
Multi-character emojis
Country flags
Skin tones
Rainbow flag and other ZWJ sequences
Chapter Summary
Further Reading
5. Record-like data structures
What’s new in this chapter
Overview of data class builders
Main features
Classic Named Tuples
Typed Named Tuples
Type hints 101
No runtime effect
Variable annotation Syntax
The meaning of variable annotations
More about @dataclass
Field options
Post-init processing
Typed class attributes
Initialization variables that are not fields
@dataclass Example: Dublin Core Resource Record
Data class as a code smell
Data class as scaffolding
Data class as intermediate representation
Parsing binary records with struct
Structs and Memory Views
Should we use struct?
Chapter Summary
Further Reading
6. Object References, Mutability, and Recycling
What’s new in this chapter
Variables Are Not Boxes
Identity, Equality, and Aliases
Choosing Between == and is
The Relative Immutability of Tuples
Copies Are Shallow by Default
Deep and Shallow Copies of Arbitrary Objects
Function Parameters as References
Mutable Types as Parameter Defaults: Bad Idea
Defensive Programming with Mutable Parameters
del and Garbage Collection
Weak References
The WeakValueDictionary Skit
Limitations of Weak References
Tricks Python Plays with Immutables
Chapter Summary
Further Reading
III. Functions as Objects
7. First-Class Functions
What’s new in this chapter
Treating a Function Like an Object
Higher-Order Functions
Modern Replacements for map, filter, and reduce
Anonymous Functions
The Nine Flavors of Callable Objects
User-Defined Callable Types
Function Introspection
From Positional to Keyword-Only Parameters
Positional-only parameters
Retrieving Information About Parameters
Packages for Functional Programming
The operator Module
Freezing Arguments with functools.partial
Chapter Summary
Further Reading
8. Type Hints in Functions
What’s new in this chapter
About gradual typing
Gradual typing in practice
Starting with Mypy
Making Mypy More Strict
A Default Parameter Value
Using None as a default
Type hints for Python 2.7 and 3.x
Types are defined by supported operations
Types usable in annotations
The Any type
Simple types and classes
Optional and Union types
Generic collections
Tuple
Generic mappings
TypedDict
Abstract Base Classes
Iterable
Parameterized generics and TypeVar
Protocols
Callable
NoReturn
Overloaded signatures
Annotating positional-only and variadic parameters
Reading annotations at runtime
Chapter summary
Further Reading
9. Decorators and Closures
What’s new in this chapter
Decorators 101
When Python Executes Decorators
Variable Scope Rules
Closures
The nonlocal Declaration
Implementing a Simple Decorator
How It Works
Decorators in the Standard Library
Memoization with functools.lru_cache
Single Dispatch Generic Functions
Parameterized Decorators
A Parameterized Registration Decorator
The Parameterized Clock Decorator
Chapter Summary
Further Reading
10. Design Patterns with First-Class Functions
What’s new in this chapter
Case Study: Refactoring Strategy
Classic Strategy
Function-Oriented Strategy
Choosing the Best Strategy: Simple Approach
Finding Strategies in a Module
Decorator-Enhanced Strategy Pattern
Command
Chapter Summary
Further Reading
IV. Classes and Protocols
11. A Pythonic Object
What’s new in this chapter
Object Representations
Vector Class Redux
An Alternative Constructor
classmethod Versus staticmethod
Formatted Displays
A Hashable Vector2d
Private and “Protected” Attributes in Python
Saving Memory with __slots__
The Problems with __slots__
Overriding Class Attributes
Implementing a typing protocol
Chapter Summary
Further Reading
12. Sequence Hacking, Hashing, and Slicing
What’s new in this chapter
Vector: A User-Defined Sequence Type
Vector Take #1: Vector2d Compatible
Protocols and Duck Typing
Vector Take #2: A Sliceable Sequence
How Slicing Works
A Slice-Aware __getitem__
Vector Take #3: Dynamic Attribute Access
Vector Take #4: Hashing and a Faster ==
Vector Take #5: Formatting
Chapter Summary
Further Reading
Search in book...
Toggle Font Controls
Playlists
Add To
Create new playlist
Name your new playlist
Playlist description (optional)
Cancel
Create playlist
Sign In
Email address
Password
Forgot Password?
Create account
Login
or
Continue with Facebook
Continue with Google
Sign Up
Full Name
Email address
Confirm Email Address
Password
Login
Create account
or
Continue with Facebook
Continue with Google
Prev
Previous Chapter
1. The Python Data Model
Next
Next Chapter
2. An Array of Sequences
Part II.
Data Structures
Add Highlight
No Comment
..................Content has been hidden....................
You can't read the all page of ebook, please click
here
login for view all page.
Day Mode
Cloud Mode
Night Mode
Reset