Lutz, Mark

Learning python/ Mark Lutz. - 5th. ed. - Mumbai : SPD : 2013 - l,1540p. : ill. ; 24cm.

"Updated for 3.3 and 2.7"--Cover. Includes index.

Part I. Getting Started
1. A Python Q&A Session .
Why Do People Use Python?
Software Quality
Developer Productivity
Is Python a "Scripting Language"?
OK, but What's the Downside?
Who Uses Python Today?
What Can I Do with Python?
Systems Programming
GUIs
Internet Scripting
Component Integration
Database Programming
Rapid Prototyping
Numeric and Scientific Programming
And More: Gaming, Images, Data Mining, Robots, Excel.
How Is Python Developed and Supported?
Open Source Tradeoffs
What Are Python's Technical Strengths?
It's Object-Oriented and Functional
It's Free
It's Portable
It's Powerful
It's Mixable
It's Relatively Easy to Use
It's Relatively Easy to Learn
It's Named After Monty Python
How Does Python Stack Up to Language X?
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
2. How Python Runs Programs
Introducing the Python Interpreter
Program Execution
The Programmer's View
Python's View
Execution Model Variations
Python Implementation Alternatives
Execution Optimization Tools
Frozen Binaries
Future Possibilities?
Chapter Summary
Test Your Knowledge: Quiz
Tiest Your Knowledge: Answers
3. How You Run Programs
The Interactive Prompt
Starting an Interactive Session
The System Path
New Windows Options in 3.3: PATH, Launcher
Where to Run: Code Directories
What Not to Type: Prompts and Comments
Running Code Interactively
Why the Interactive Prompt?
Usage Notes: The Interactive Prompt
System Command Lines and Files
A First Script
Running Files with Command Lines
Command-Line Usage Variations
Usage Notes: Command Lines and Files
Unix-Style Executable Scripts: #!
Unix Script Basics
The Unix env Lookup Trick
The Python 3.3 Windows Launcher: #! Comes to Windows
Clicking File Icons
Icon-Click Basics
Clicking Icons on Windows
The input Trick on Windows
Other Icon-Click Limitations
Module Imports and Reloads
Import and Reload Basics
The Grander Module Stor\': Attributes
Usage Notes: import and reload
Using exec to Run Module Files
The IDLE User Interface
IDLE Startup Details
IDLE Basic Usage
IDLE Usability Features
Advanced IDLE Tools
Usage Notes: IDLE
Other IDEs
Other Launch Options
Embedding Calls
Frozen Binary Executables
Text Editor Launch Options
Still Other Launch Options
Future Possibilities?
Which Option Should I Use?
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
Test Your Knowledge: Part I Exercises
Part II. Types and Operations
4. introducing Python Object Types
The Python Conceptual Hierarchy
Why Use Built-in Types?
Python's Core Data Types
Numbers
Strings
Sequence Operations
Immutability
Type-Specific Methods
, Getting Help
Other Ways to Code Strings
Unicode Strings
Pattern Matching
Lists
Sequence Operations
Type-Sp ic Operations
Bounds Checking
Nesting
Comprehensions
Dictionaries
Mapping Operations
Nesting Revisited
Missing Keys; if Tests
Sorting Keys: for Loops
Iteration and Optimization
Tuples
Why Tuples?
Files
Binary Bytes Files
Unicode Text Files
Other File-Like Tools
Other Core Types
How to Break Your Code's Flexibility
User-Defined Classes
And Everything Else
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
5. Numeric Types
Numeric Type basics
Numeric Literals
Built-in Numeric Tools
Python Expression Operators
Numbers in Action
Variables and Basic Expressions
Numeric Display Formats
Comparisons: Normal and Chained
Division: Classic, Floor, and True
Integer Precision
Complex Numbers
Hex, Octal, Binary: Literals and Conversions
Bitwise Operations
Other Built-in Numeric Tools
Other Numeric Types
Decimal Type
Fraction Type
Sets
Booleans
Numeric Extensions
Chapter Summarv-
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
6. The Dynamic Typing interlude
The Case of the Missing Declaration Statements
Variables, Objects, and References
Types Live with Objects, Not Variables
Objects Are Garbage-Collected
Shared References
Shared References and In-Place Changes
Shared References and Equality
Dynamic Typing Is Everywhere
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
7. String Fundamentals
This Chapter's Scope
Unicode: The Short Story
String Basics
String Literals
Single- and Double-Quoted Strings Are the Same
Escape Sequences Represent Special Characters
Raw Strings Suppress Escapes
Triple Quotes Code Multiline Block Strings
Strings in Action
Basic Operations
Indexing and Slicing
String Conversion Tools
Changing Strings I
String Methods
Method Call Syntax
Methods of Strings
String Method Examples: Changing Strings II
String Method Examples: Parsing Text
Other Common String Methods in Action
The Original string Module's Functions (Gone in 3.X)
String Formatting Expressions
Formatting Expression Basics
Advanced Formatting Expression Syntax
Advanced Formatting Expression Examples
Dictionary-Based Formatting Expressions
String Formatting Method Calls
Formatting Method Basics
Adding Keys, Attributes, and Offsets
Advanced Formatting Method Syntax
Advanced Formatting Method Examples
Comparison to the % Formatting Expression
Why the Format Method?
General Type Categories
Types Share Operation Sets by Categories
Mutable Types Can Be Changed in Place
Chapter Summary
Test Your Knowledge; Quiz
Test Your Knowledge: Answers
8. Lists and Dictionaries
Lists
Lists in Action
Basic List Operations
List Iteration and Comprehensions
Indexing, Slicing, and Matrixes
Changing Lists in Place
Dictionaries
Dictionaries in Action
Basic Dictionary Operations
Changing Dictionaries in Place
More Dictionary Methods
Example: Movie Database
Dictionary Usage Notes
Other Ways to Make Dictionaries
Dictionary Changes in Python 3.X and 2.7
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
9. Tuples, Files, and Everything Else
Tuples
Tuples in Action
Why Lists and Tuples?
Records Revisited: Named Tuples
Files
Opening Files
Using Files
Files in Action
Text and Binar>' Files; The Short Story
Storing Python Objects in Files: Conversions
Storing Native Python Objects: pickle
Storing Python Objects in JSON Format
Storing Packed Binary- Data: struct
File Context Managers
Other File Tools
Core Types Review and Summary
Object Flexibility
References Versus Copies
Comparisons, Equality, and Truth
The Meaning of True and False in Python
Python's Type Hierarchies
Type Objects
Other Types in Python
Built-in Type Gotchas
Assignment Creates References, Not Copies
Repetition Adds One Level Deep
Beware of Cyclic Data Structures
Immutable Types Can't Be Changed in Place
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
Test Your Knowledge: Part II Exercises
Part III. Statements and Syntax
10. Introducing Python Statements
The Python Conceptual Hierarchy Revisited
Python's Statements
A Tale of Two ifs
What Python Adds
What Python Removes
Why Indentation Syntax?
A Few Special Cases
A Quick Example: Interactive Loops
A Simple Interactive Loop
Doing Math on User Inputs
Handling Errors by Testing Inputs
Handling Errors with try Statements
Nesting Code Three Levels Deep
CViapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
11. Assignments, Expressions, and Prints
Assignment Statements
Assignment Statement Forms
Sequence Assignments
Extended Sequence Unpacking in Python 3.X
Multiple-Target Assignments
Augmented Assignments
Variable Name Rules
Expression Statements
Expression Statements and In-Place Changes
Print Operations
The Python 3.X print Function
The Python 2.X print Statement
Print Stream Redirection
Version-Neutral Printing
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
12. ifTests and Syntax Rules
if Statements
General Format
Basic Examples
Multiway Branching
Python Syntax Revisited
Block Delimiters: Indentation Rules
Statement Delimiters: Lines and Continuations
A Few Special Cases
Truth Values and Boolean Tests
The if/else Ternary Expression
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
13. while and for Loops
while Loops
General Format
Examples
break, continue, pass, and the Loop else
General Loop Format
pass
continue
break
Loop else
for Loops
General Format
Examples
Loop Coding Techniques
Counter Loops: range
Sequence Scans: while and range Versus for
Sequence Shufflers: range and len
Nonexhaustive Traversals: range Versus Slices
Changing Lists: range Versus Comprehensions
Parallel Traversals: zip and map
Generating Both Offsets and Items: enumerate
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
14. Iterations and Comprehensions
Iterations: A First Look
The Iteration Protocol: File Iterators
Manual Iteration: iter and next
Other Built-in Type Iterables
List Comprehensions: A First Detailed Look
List Comprehension Basics
Using List Comprehensions on Files
Extended List Comprehension Syntax
Other Iteration Contexts
New Iterables in Python 3.X
Impacts on 2.X Code: Pros and Cons
The range Iterable
The map, zip, and filter Iterables
Multiple Versus Single Pass Iterators
Dictionary View Iterables
Other Iteration Topics
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
15. The Documentation Interlude
Python Documentation Sources
# Comments
The dir Function
Docstrings; ^doc—
PyDoc; The help Function
PyDoc; HTML Reports
Beyond docstrings: Sphinx
The Standard Manual Set
- Web Resources
Published Books
Common Coding Gotchas
Chapter Summary
Test Your Knowledge; Quiz
Test Your Knowledge: Answers
Test Your Knowledge: Part 111 Exercises
Part IV. Functions and Generators
16. Function BasiG
Why Use Functions?
Coding Functions
def Statements
def Executes at Runtime
A First Example: Definitions and Calls
Definition
Calls
Polymorphism in Python
A Second Example: Intersecting Sequences
Definition
Calls
Polymorphism Revisited
Local Variables
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
17. Scopes
Python Scope Basics
Scope Details
Name Resolution: The LEGB Rule
Scope Example
The Built-in Scope
The global Statement
Program Design: Minimize Global Variables
Program Design; Minimize Cross-File Changes
Other Ways to Access Globals
Scopes and Nested Functions
Nested Scope Details
Nested Scope Examples
Factory Functions: Closures
Retaining Enclosing Scope State with Defaults
The nonlocal Statement in 3.X
nonlocal Basics
nonlocal in Action
Why nonlocal? State Retention Options
State with nonlocal: 3.X only
State with Globals: A Single Copy Only
State with Classes: Explicit Attributes (Preview)
State with Function Attributes: 3.X and 2.X
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
18. Arguments
Argument-Passing Basics
Arguments and Shared References
Avoiding Mutable Argument Changes
Simulating Output Parameters and Multiple Results
Special Argument-Matching Modes
Argument Matching Basics
Argument Matching Syntax
The Gritty Details
Keyword and Default Examples
Arbitrary Arguments Examples
Python 3.x Keyword-Only Arguments
The min Wakeup Call!
Full Credit
Bonus Points
The Punch Line...
Generalized Set Functions
Emulating the Python 3.X print Function
Using Keyword-Only Arguments
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
19. Advanced Function TopiG
Function Design Concepts
Recursive Functions
Summation with Recursion
Coding Alternatives
Loop Statements Versus Recursion
Handling Arbitrary Structures
Function Objects; Attributes and Annotations
Indirect Function Calls: "First Class" Objects
Function Introspection
Function Attributes
Function Annotations in 3.X
Anonymous Functions: lambda
lambda Basics
Why Use lambda?
How (Not) to Obfuscate Your Python Code
Scopes: lambdas Can Be "Nested Too
Functional Programming Tools
Mapping Functions over Iterables: map
Selecting Items in Iterables: filter
Combining Items in Iterables: reduce
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
20. Comprehensions and Generations
List Comprehensions and Functional Tools
List Comprehensions Versus map
Adding Tests and Nested Loops: filter
Example: List Comprehensions and Matrixes
Don't Abuse List Comprehensions: KISS
Generator Functions and Expressions
Generator Functions: yield Versus return
Generator Expressions: Iterables Meet Comprehensions
Generator Functions Versus Generator Expressions
Generators Are Single-Iteration Objects
Generation in Built-in Types, Tools, and Classes
Example: Generating Scrambled Sequences
Don't Abuse Generators: EIBTI
Example: Emulating zip and map with Iteration Tools
Comprehension Syntax Summary
Scopes and Comprehension Variables
Comprehending Set and Dictionary Comprehensions
Extended Comprehension Syntax for Sets and Dictionaries
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
21. The Benchmarking interlude
Timing Iteration Alternatives
Timing Module: Homegrown
Timing Script
Timing Results
Timing Module Alternatives
Other Suggestions
Timing Iterations and Pythons with timeit
Basic timeit Usage
Benchmark Module and Script: timeit
Benchmark Script Results
More Fun with Benchmarks
Other Benchmarking Topics: pystones
Function Gotchas
Local Names Are Detected Statically
Defaults and Mutable Objects
Functions Without returns
Miscellaneous Function Gotchas
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
Test Your Knowledge: Part IV Exercises
Part V. Modules and Packages
22. Modules: The Big Picture
why Use Modules?
Python Program Architecture
How to Structure a Program
Imports and Attributes
Standard Library Modules
How Imports Work
1. Find It
2. Compile It (Maybe)
3. Run It
Byte Code Files: _pycache_ in Python 3.2+
Byte Code File Models in Action
The Module Search Path
Configuring the Search Path
Search Path Variations
The sys.path List
Module File Selection
Chapter Summary
' Test Your Knowledge; Quiz
Test Your Knowledge: Answers
23. Module Coding Basis
Module Creation
Module Filenames
Other Kinds of Modules
Module Usage
The import Statement
The from Statement
The from * Statement
Imports Happen Only Once
import and from Are Assignments
import and from Equivalence
Potential Pitfalls of the from Statement
Module Namespaces
Files Generate Namespaces
Namespace Dictionaries: diet
Attribute Name Qualification
Imports Versus Scopes
Namespace Nesting
Reloading Modules
reload Basics
reload Example
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
24. Module Packages
Package Import casics
Packages and Search Path Settings
Package init .py Files
Package Import Example
from Versus import with Packages
Why Use Package Imports?
A Tale of Three Systems
Package Relative Imports
Changes in Python 3.X
Relative Import Basics
Why Relative Imports?
The Scope of Relative Imports
Module Lookup Rules Summars-
Relative Imports in Action
Pitfalls of Package-Relative Imports: Mixed Use
Python 3.3 Namespace Packages
Namespace Package Semantics
Impacts on Regular Packages: Optional —init—.py
Namespace Packages in Action
Namespace Package Nesting
Files Still Have Precedence over Directories
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
25. Advanced Module Topics
Module Design Concepts
Data Hiding in Modules
Minimizing from * Damage: _X and —all—
Enabling Future Language Features: —future—
Mixed Usage Modes: name and —main—
Unit Tests with name—
Example; Dual Mode Code
Currency Symbols: Unicode in Action
Docstrings: Module Documentation at Work
Changing the Module Search Path
The as Extension for import and from
Example: Modules Are Objects
Importing Modules by Name String
Running Code Strings
Direct Calls: Two Options
Example: Transitive Module Reloads
A Recursive Reloader
Alternative Codings
Module Gotchas
Module Name Clashes: Package and Package-Relative Imports
Statement Order Matters in Top-Level Code
from Copies Names but Doesn't Link
from * Can Obscure the Meaning of Variables
reload May Not Impact from Imports
V id, from, and Interactive Testing
Recursive from Imports May Not Work
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
Test Your Knowledge: Part V Exercises
Part VI. Classes and OOP
26. OOP: The Big Picture
Why Use Classes?
OOP from 30,000 Feet
Attribute Inheritance Search
Classes and Instances
Method Calls
Coding Class Trees .
Operator Overloading
OOP Is About Code Reuse
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
27. Class Coding Basics
Classes Generate Multiple Instance Objects
Class Objects Provide Default Behavior
Instance Objects Are Concrete Items
A First Example
Classes Are Customized by Inheritance
A Second Example
Classes Are Attributes in Modules
Classes Can Intercept Python Operators
A Third Example
Why Use Operator Overloading?
The World's Simplest Python Class
Records Revisited: Classes Versus Dictionaries
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
28. A More Realistic Example .
Step 1: Making Instances
Coding Constructors
Testing As You Go
Using Code Two Ways
Step 2: Adding Behavior Metliods
Coding Methods
Step 3: Operator Overloading
Koviding Print Displays
Step 4: Customizing Behavior by Subclassing
Coding Subclasses
Augmenting Methods: The Bad W ay
Augmenting Methods; The Ciood \\ ay
Polymorphism in Action
Inherit, Customize, and Extend
OOP: The Big Idea
Step 5: Customizing Constructors, Too
OOP Is Simpler Than You May Think
Other Ways to Combine Classes
Step 6: Using Introspection Tools
Special Class Attributes
A Generic Display Tool
Instance Versus Class Attributes
Name Considerations in Tool Classes
Our Classes' Final Form
Step 7 (Final): Storing Objects in a Database
Pickles and Shelves
Storing Objects on a Shelve Database
Exploring Shelves Interactively
Updating Objects on a Shelve
Future Directions
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
29. Class Coding Details
The class Statement
General Form
Example
Methods
Method Example
Calling Superclass Constructors
Other Method Call Possibilities
Inheritance
Attrib te Tree Construction
Spe uzing Inherited Methods
Class Interface Techniques
Abstract Superclasses
Namespaces: The Conclusion
Simple Names: Global Unless Assigned
Attribute Names: Object Namespaces
The "Zen" of Namespaces: Assignments Classify Names
Nested Classes: The LEGS Scopes Rule Revisited
Namespace Dictionaries: Review
Namespace Links: A Tree Climber
Documentation Strings Revisited
Classes Versus Modules
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
30. Operator Overloading
The Basics
Constructors and Expressions: init and sub
Common Operator Overloading Methods
Indexing and Slicing: getitem and ^setitem
Intercepting Slices
Slicing and Indexing in Python 2.X
But 3.X's index Is Not Indexing!
Index Iteration: getitem
Iterable Objects: iter and next_
User-Defined Iterables
Multiple Iterators on One Object
Coding Alternative: iter plus yield
Membership: contains , iter , and getitem
Attribute Access: getattr and ^setattr
Attribute Reference
Attribute Assignment and Deletion
Other Attribute Management Tools
Emulating Privacy for Instance Attributes: Part 1
String Representation: repr and str
Why Two Display Methods?
Display Usage Notes
Right-Side and In-Place Uses: radd and iadd
Right-Side Addition
In-Place Addition
Call Expressions: call
Function Interfaces and Callback-Based Code
Comparisons: _lt_, __gt_, and Others
The cmp_ Method in Python 2.X
Boolean Tests: boo! and .len
Boolean Methods in Python 2.X
Object Destruction: del
Destructor Usage Notes
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
31. Designing with Classes
Python and OOP
Polymorphism Means Interfaces, Not Call Signatures
OOP and Inheritance: "Is-a" Relationships
OOP and Composition: "Has-a" Relationships
Stream Processors Revisited
OOP and Delegation: "Wrapper" Proxy Objects
Pseudoprivate Class Attributes
Name Mangling Overview
Why Use Pseudoprivate Attributes?
Methods Are Objects: Bound or Unbound
Unbound Methods Are Functions in 3.X
Bound Methods and Other Callable Objects
Classes Are Objects: Generic Object Factories
Why Factories?
Multiple Inheritance: "Mix-in" Classes
Coding Mix-in Display Classes
Other Design-Related Topics
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
32. Advanced Class Topics
Extending Built-in Types
Extending Types by Embedding
Extending Types by Subclassing
The "New Style" Class Model
Just How New Is New-Style?
New-Style Class Changes
Attribute Fetch for Built-ins Skips Instances
Type Model Changes
All Classes Derive from "object"
Diamond Inheritance Change
More on the MRO: Method Resolution Order
Example: Mapping Attributes to Inheritance Sources
New-Style Class Extensions
Slots; Attribute Declarations
Properties: Attribute Accessors
_getattribute_ and Descriptors: Attribute Tools
Other Class Changes and Extensions
- Static and Class Methods
Why the Special Methods?
Static Methods in 2.X and 3.X
Static Method Alternatives
Using Static and Class Methods
Counting Instances with Static Methods
Counting Instances with Class Methods
Decorators and Metaclasses: Part 1
Function Decorator Basics
A First Look at User-Defined Function Decorators
A First Look at Class Decorators and Metaclasses
For More Details
The super Built-in Function: For Better or Worse?
The Great super Debate
Traditional Superclass Call Form: Portable, General
Basic super Usage and Its Tradeoffs
The super Upsides: Tree Changes and Dispatch
Runtime Class Changes and super
Cooperative Multiple Inheritance Method Dispatch
The super Summary
Class Gotchas
Changing Class Attributes Can Have Side Effects
Changing Mutable Class Attributes Can Have Side Effects, Too
Multiple Inheritance: Order Matters
Scopes in Methods and Classes
Miscellaneous Class Gotchas
KISS Revisited: "Overwrapping-itis"
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
Test Your Knowledge: Part VI Exercises
Part VII. Exceptions and Tools
33. Exception Basics
Why Use Exceptions?
Exception Roles
Exceptions: The Short Story
Default Exception Handler
Catching Exceptions
Raising Exceptions
User-Defined Exceptions
Termination Actions
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
34. Exception Coding Details
The try/except/else Statement
How try Statements Work
try Statement Clauses
The try else Clause
Example: Default Behavior
Example: Catching Built-in Exceptions
The try/finally Statement
Example: Coding Termination Actions with try/finally
Unified try/except/finally
Unified try Statement Syntax
Combining finally and except by Nesting
Unified try Example
The raise Statement
Raising Exceptions
Scopes and try except Variables
Propagating Exceptions with raise
Python 3.x Exception Chaining: raise from
The assert Statement
Example: Trapping Constraints (but Not Errors!)
with/as Context Managers
Basic Usage
The Context Management Protocol
Multiple Context Managers in 3.1, 2.7, and Later
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
35. Exception Objects
Exceptions: Back to the Future
String Exceptions Are Right Out!
r ss-Based Exceptions
ding Exceptions Classes
Why Exception Hierarchies?
Built-in Exception Classes
Built-in Exception Categories
Default Printing and State
Custom Print Displays
Custom Data and Behavior
" Providing Exception Details
Providing Exception Methods
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
36. Designing with Exceptions
Nesting Exception Handlers
Example: Control-Flow Nesting
Example: Syntactic Nesting
Exception Idioms
Breaking Out of Multiple Nested Loops: "go to"
Exceptions Aren't Always" Errors
Functions Can Signal Conditions with raise
Closing Files and Server Connections
Debugging with Outer try Statements
Running In-Process Tests
More on sys.exc_info
Displaying Errors and Tracebacks
Exception Design Tips and Gotchas
Wl\at Should Be Wrapped
Catching Too Much: Avoid Empty except and Exception
Catching Too Little: Use Class-Based Categories
Core Language Summary
The Python Toolset
Development Tools for Larger Projects
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
Test Your Knowledge: Part VII Exercises
Partviii. Advanced Topics
37. Unicode and Byte Strings
String Changes in 3.X
String Basics
Character Encoding Schemes
How Python Stores Strings in Memory
Python's String Types
Text and Binary Files
Coding Basic Strings
Python 3.x String Literals
Python 2.x String Literals
String Type Conversions
Coding Unicode Strings
Coding ASCII Text
Coding Non-ASCII Text
Encoding and Decoding Non-ASCII text
Other Encoding Schemes
Byte String Literals: Encoded Text
Converting Encodings
Coding Unicode Strings in Python 2.X
Source File Character Set Encoding Declarations
Using 3.x bytes Objects
Method Calls
Sequence Operations
Other 'Ways to Make bytes Objects
Mixing String Types
Using 3.X/2.6+ bytearray Objects
bytearrays in Action
Python 3.x String Types Summary
Using Text and Binary Files
Text File Basics
Text and Binary Modes in 2.X and 3.X
Type and Content Mismatches in 3.X
Using Unicode Files
Reading and Writing Unicode in 3.X
Handling the BOM in 3.X
Unicode Files in 2.X
Unicode Filenames and Streams
Other String Tool Changes in 3.X
The re Pattern-Matching Module
The struct Binary Data Module
The pickle Object Serialization Module
XML Parsing Tools
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
38. Managed Attributes
Why Manage Attributes?
Inserting Code to Run on Attribute Access
Properties
The Basics
A First Example
Computed Attributes
Coding Properties with Decorators
Descriptors
The Basics
A First Example
Computed Attributes
Using State Information in Descriptors
How Properties and Descriptors Relate
getattr and getattribute
The Basics
A First Exaniple
Computed Attributes
getattr and getattribute Compared
Management Techniques Compared
Intercepting Built-in Operation Attributes
Example: Attribute Validations
Using Properties to Validate
Using Descriptors to Validate
Using getattr to Validate
Using getattribute to Validate
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
39. Decorators
What's a Decorator?
Managing Calls and Instances
Managing Functions and Classes
Using and Defining Decorators
Why Decorators?
The Basics
Function Decorators
Class Decorators
Decorator Nesting
Decorator Arguments
Decorators Manage Functions and Classes, Too
Coding Function Decorators
Tracing Calls
Decorator State Retention Options
Class Blunders I: Decorating Methods
Timing Calls
Adding Decorator Arguments
Coding Class Decorators
Singleton Classes
Tracing Object Interfaces
Class Blunders II: Retaining Multiple Instances
Decorators Versus Manager Functions
Why Decorators? (Revisited)
Managing Functions and Classes Directly
Example: "Private" and "Public" Attributes
Implementing Private Attributes
Implementation Details I
Generalizing for Public Declarations, Too
Implementation Details II
Open Issues
Python Isn't About Control
Example: Validating Function Arguments
The Goal
A Basic Range-Testing Decorator for Positional Arguments
Generalizing for Keywords and Defaults, Too
Implementation Details
Open Issues
Decorator Arguments Versus Function Annotations
Other Applications: Type Testing (If You Insist!)
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers
40. Metaclasses
To Metaclass or Not to Metaclass
Increasing Levels of "Magic"
A Language of Hooks
The Downside of "Helper" Functions
Metaclasses Versus Class Decorators: Round 1
The Metaclass Model
Classes Are Instances of type
Metaclasses Are Subclasses of Type
Class Statement Protocol
Declaring Metaclasses
Declaration in 3.X
Declaration in 2.X
Metaclass Dispatch in Both 3.X and 2.X
Coding Metaclasses
A Basic Metaclass
Customizing Construction and Initialization
Other Metaclass Coding Techniques
Inheritance and Instance
Metaclass Versus Superclass
Inheritance: The Full Story
Metaclass Methods
Metaclass Methods Versus Class Methods
Operator Overloading in Metaclass Methods
Example: Adding Methods to Classes
Manual Augmentation
Metaclass-Based Augmentation
Metaclasses Versus Class Decorators: Round 2
Example: Applying Decorators to Methods
Tracing with Decoration Manually
Tracing with Metaclasses and Decorators
Applying Any Decorator to Methods
Metaclasses Versus Class Decorators: Round 3 (and Last)
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers

9781449355739 (paperback)


Python (Computer program language)
Object-oriented programming (Computer science)

005.133 / LUT/L