Index

Symbols

= and == (equality operators), Comparisons, Equality, and Truth

* (repetition) operator, Basic List Operations

@ symbol, Function Decorator Basics

\ (backslash), Statement rule special cases, A Few Special Cases

\ (backslash) escape sequences, Other Ways to Code Strings

& (bitwise AND operator), Python Expression Operators

| (bitwise or operator), Python Expression Operators

^ (bitwise XOR operator), Python Expression Operators

: (colon), What Python Adds, Common Coding Gotchas

{ } (curly braces), Python’s Core Data Types, Python Expression Operators, Statement rule special cases

dictionaries and, Mapping Operations, Dictionaries
set comprehensions and, Set comprehensions in Python 3.0
sets and, Set literals in Python 3.0, Dictionary views and sets

/ and // (division operators), Python Expression Operators

(see also division)

" (double quotes) and strings, Single- and Double-Quoted Strings Are the Same

... (ellipses), pass

= and == (equality operators), Python Expression Operators, Shared References and Equality

#! (hash bang), Unix Executable Scripts (#!)

# (hash character), A First Script, # Comments

>, >=, <, <= (magnitude comparison operators), Python Expression Operators

– (minus operator), Python Expression Operators

* (multiplication operator), Python Expression Operators

( ) (parentheses), Parentheses are optional, Statement rule special cases, A Few Special Cases

functions and, Common Coding Gotchas
generator expressions and, Generator Expressions: Iterators Meet Comprehensions
tuples and, Tuples

+ (plus operator), Python Expression Operators, Basic List Operations

"\u..." and "\U..." escapes, Coding Unicode Strings in Python 2.6

% (remainder operator), Python Expression Operators

; (semicolon), End of line is end of statement, Statement rule special cases

>> and << (shift operators), Python Expression Operators

' (single quotes) and strings, Single- and Double-Quoted Strings Are the Same

[ ] (square brackets), Python’s Core Data Types, Python Expression Operators, Statement rule special cases

dictionaries and, Dictionaries in Action
list comprehensions and, List Comprehension Basics, List Comprehensions Versus map, Coding your own zip(...) and map(None, ...)
lists and, Comprehensions, Lists

_ (underscore), Minimizing from * Damage: _X and __all__

__add__ method, A Third Example

__all__ variable, Minimizing from * Damage: _X and __all__

__bases__ attribute, Namespace Dictionaries, Namespace Links

__bool__ method, Boolean Tests: __bool__ and __len__

__call__ method, Call Expressions: __call__

function interfaces and, Function Interfaces and Callback-Based Code

__class__ attribute, Namespace Dictionaries, Namespace Links

__cmp__ method (Python 2.6), Comparisons: __lt__, __gt__, and Others

__contains__ method, Membership: __contains__, __iter__, and __getitem__

__del__ method, Object Destruction: __del__

__delattr__ method, __getattr__ and __getattribute__

__delete__ method, Read-only descriptors

__dict__ attribute, Files Generate Namespaces

__doc__ attribute, Docstrings: __doc__, Documentation Strings Revisited

__enter__ method, The Context Management Protocol

__eq__ method, Comparisons: __lt__, __gt__, and Others

__exit__ method, The Context Management Protocol

__get__ method, Common Operator Overloading Methods, Descriptor method arguments

__getattr__ method, Attribute Reference: __getattr__ and __setattr__, Delegation-Based Classes in 3.0: __getattr__ and built-ins, Inserting Code to Run on Attribute Access, __getattr__ and __getattribute__, Delegation-Based Managers Revisited

computed attributes, Computed Attributes
delegation using, OOP and Delegation: “Wrapper” Objects
delegation-based managers, Delegation-Based Managers Revisited
example, A First Example
interception of built-in attributes, Intercepting Built-in Operation Attributes
loops, avoiding in interception methods, Avoiding loops in attribute interception methods
__getattribute__, compared to, __getattr__ and __getattribute__ Compared

__getattribute__ method, __getattribute__ and Descriptors, Inserting Code to Run on Attribute Access, __getattr__ and __getattribute__, Delegation-Based Managers Revisited

computed attributes, Computed Attributes
delegation-based managers, Delegation-Based Managers Revisited
example, A First Example
interception of built-in operation attributes, Intercepting Built-in Operation Attributes
loops, avoiding in attribute interception, Avoiding loops in attribute interception methods
__getattr__, compared to, __getattr__ and __getattribute__ Compared

__getitem__ method, Indexing and Slicing: __getitem__ and __setitem__

index iteration, Index Iteration: __getitem__
membership, Membership: __contains__, __iter__, and __getitem__

__gt__ method, Comparisons: __lt__, __gt__, and Others

__iadd__ method, Right-Side and In-Place Addition: __radd__ and __iadd__

__init__.py files, Package __init__.py Files

__init__ method, Classes Can Intercept Python Operators, Coding Constructors, Constructors and Expressions: __init__ and __sub__

__iter__ method, Iterator Objects: __iter__ and __next__

design purpose, User-Defined Iterators
membership, Membership: __contains__, __iter__, and __getitem__

__len__ method, Boolean Tests: __bool__ and __len__

__lt__ method, Comparisons: __lt__, __gt__, and Others

__main__ attribute

__name__ attribute of modules and, Mixed Usage Modes: __name__ and __main__

__main__ module, Scope Rules

__metaclass__ variable (Python 2.6), Declaring Metaclasses

__name__ attribute, Mixed Usage Modes: __name__ and __main__, Using Code Two Ways

command-line arguments with, Using Command-Line Arguments with __name__
unit tests, Unit Tests with __name__

__ne__ method, Comparisons: __lt__, __gt__, and Others

__next__ method, The Iteration Protocol: File Iterators, Iterator Objects: __iter__ and __next__

__radd__ method, Right-Side and In-Place Addition: __radd__ and __iadd__

__repr__ method, String Representation: __repr__ and __str__

custom exception display using, Custom Print Displays

__set__ method, Common Operator Overloading Methods, Read-only descriptors

__setattr__ method, Attribute Reference: __getattr__ and __setattr__, Inserting Code to Run on Attribute Access, __getattr__ and __getattribute__

__setitem__ method, Intercepting Slices

__slots__ attribute, Listing attributes per object in class trees, Instance Slots

descriptors and, How Properties and Descriptors Relate
__dict__ attribute and, Using __dict__ and __slots__

__str__ method, A Third Example, String Representation: __repr__ and __str__

custom exception display using, Custom Print Displays
overload method for printing objects, Providing Print Displays

__sub__ method, Constructors and Expressions: __init__ and __sub__

A

abs function, Other Built-in Numeric Tools

absolute imports, Relative Import Basics

abstract superclasses, Abstract Superclasses, Python 2.6 and 3.0 Abstract Superclasses

example, Stream Processors Revisited
Python 2.6 and 3.0, Python 2.6 and 3.0 Abstract Superclasses

accessor functions, Minimize Cross-File Changes

ActivePython, Where to Get Python

annotation information, Function Annotations in 3.0

anonymous functions, Anonymous Functions: lambda

anydbm module (Python 2.6), Pickles and Shelves

append method, Type-Specific Operations, List method calls, Common Coding Gotchas

apply built-in (Python 2.6), The defunct apply built-in (Python 2.6)

arbitrary arguments examples

apply built-in (Python 2.6), The defunct apply built-in (Python 2.6)
applying functions generically, Applying functions generically
collecting arguments, Collecting arguments
unpacking arguments, Unpacking arguments

arguments, Arguments

argument passing basics, Argument-Passing Basics, Simulating Output Parameters
mutable argument changes, avoiding, Avoiding Mutable Argument Changes
output parameters, simulating, Simulating Output Parameters
shared references, Arguments and Shared References
argument-matching modes, Special Argument-Matching Modes, Why keyword-only arguments?
arbitrary arguments examples, Arbitrary Arguments Examples, The defunct apply built-in (Python 2.6)
available modes, The Basics
defaults, Defaults
keyword-only arguments (Python 3.0), Python 3.0 Keyword-Only Arguments
keywords, Keywords
keywords and defaults combined, Combining keywords and defaults
matching syntax, Matching Syntax
ordering rules, The Gritty Details
emulating Python 3.0 print in earlier versions, Emulating the Python 3.0 print Function
keyword-only arguments, Using Keyword-Only Arguments
generalized set functions, Generalized Set Functions
keyword arguments, Using Keyword-Only Arguments
min wakeup call, The min Wakeup Call!
three ways of coding, Full Credit
using max instead of min, Bonus Points

ArithmeticError class, Built-in Exception Classes

as extension for import and from, The as Extension for import and from

ASCII character code, Character Encoding Schemes

coding ASCII text, Coding ASCII Text

assert statement, Abstract Superclasses, The assert Statement

trapping constraints example, Example: Trapping Constraints (but Not Errors!)

AssertionError exception, The assert Statement

assignment

import, from, and def, import and from Are Assignments
mutables in, Common Coding Gotchas
within function classes, Scope Rules

assignment statements, Python’s Statements, Assignment Statements, Augmented assignment and shared references

assignment statement forms, Assignment Statement Forms
augmented assignments, Augmented Assignments
sequence assignments, Sequence Assignments, Advanced sequence assignment patterns
extended sequence unpacking in Python 3.0, Extended Sequence Unpacking in Python 3.0
multiple-target assignments, Multiple-Target Assignments

associative arrays, Dictionaries

as_integer_ratio method, Built-in Numeric Tools

attribute fetches, String Methods

attribute interception methods, Increasing Levels of Magic

attribute tree construction, Attribute Tree Construction

attributes, The Grander Module Story: Attributes, How to Structure a Program, Module Creation, Coding Constructors

managed attributes (see managed attributes)

automatic memory management, It’s Powerful

B

base indicators, Numeric Literals

BaseException class, Built-in Exception Classes

basic numeric literals, Numeric Literals

basic statement form, Assignment Statement Forms

beginners’ mistakes, Common Coding Gotchas

behavior methods, Step 2: Adding Behavior Methods

binary files, Files, Text and binary files in Python 3.0, Text and Binary Files

binary numeric literals, Numeric Literals

binary-mode files, Using Text and Binary Files

in Python 3.0, Text and Binary Modes in 3.0

bitwise (binary) data, Python Expression Operators, Bitwise Operations, The struct Binary Data Module

bit_length method (Python 3.1), Built-in Numeric Tools

blank lines, Python Syntax Rules, Common Coding Gotchas

block delimiters, Block Delimiters: Indentation Rules

blocks, Python Syntax Rules

BOM (byte order marker), Text and Binary Files

Python 3.0, handling in, Handling the BOM in 3.0, Handling the BOM in 3.0

book update websites, Book Updates

bool type, The bool type

Boolean numeric type, Booleans

Boolean object type, Other Core Types

Boolean operators, Truth Tests, The if/else Ternary Expression

Booleans in Python 2.6, Boolean Tests: __bool__ and __len__

bound methods, Function Interfaces and Callback-Based Code, Methods Are Objects: Bound or Unbound

other callable objects, compared to, Bound Methods and Other Callable Objects

break statement, break, continue, pass, and the Loop else, break

bsddb extension module, Exploring Shelves Interactively

built-in exception classes, Built-in Exception Classes, Default Printing and State

categories, Built-in Exception Categories
class hierarchy, Built-in Exception Classes
default printing and state, Default Printing and State

built-in mathematical functions, Built-in Numeric Tools

built-in object types, It’s Powerful, Introducing Python Object Types, Python’s Core Data Types

additional core types, Other Core Types, And Everything Else
dictionaries, Dictionaries, Missing Keys: if Tests, Dictionaries, The has_key method is dead: long live in!
files, Files, Files, Other File Tools
issues to be aware of, Built-in Type Gotchas
assignment creates references, Assignment Creates References, Not Copies
cyclic data structures, Beware of Cyclic Data Structures
immutable types, Immutable Types Can’t Be Changed In-Place
repetition adds one level deep, Repetition Adds One Level Deep
lists, Lists, Comprehensions, Lists
numbers, Numbers
object classifications, Type Categories Revisited
sets, Other Core Types
shared properties, Type Categories Revisited
strings, Strings, Pattern Matching
tuples, Tuples, Tuples, Why Lists and Tuples?
type, How to Break Your Code’s Flexibility

built-in scope, The Built-in Scope

builtins module, Other Built-in Numeric Tools, The Built-in Scope

byte code, OK, but What’s the Downside?

compilation, Byte code compilation

byte order marker (see BOM)

bytearray, Strings

object type, using, Using 3.0 (and 2.6) bytearray Objects, Using 3.0 (and 2.6) bytearray Objects

bytearray string type, Python’s String Types

bytes, Strings

bytes object, String Changes in 3.0

data encoding in, Text and Binary Files
literals, Other Unicode Coding Techniques

bytes string type, Other Ways to Code Strings, Python’s String Types

C

C code, Common Coding Gotchas

call expressions, String Methods

calls, Calls, Calls

character encoding schemes, Character Encoding Schemes

character set encoding declarations, Source File Character Set Encoding Declarations

chmod command, Unix Executable Scripts (#!)

class attribute descriptors, Increasing Levels of Magic

class decorators, Managing Calls and Instances, Class Decorators

coding, Coding Class Decorators
decorators versus manager functions, Decorators Versus Manager Functions
retaining multiple instances, Class Blunders II: Retaining Multiple Instances
singleton classes, Singleton Classes
tracing object interfaces, Tracing Object Interfaces, Tracing Object Interfaces
implementation, Implementation
justification, Why Decorators? (Revisited)
metaclasses, compared to, Metaclasses Versus Class Decorators: Round 1, Metaclasses Versus Class Decorators: Round 2, Managing instances instead of classes, Metaclasses Versus Class Decorators: Round 3
private attributes, implementing, Implementing Private Attributes, Using __dict__ and __slots__
public attributes, implementing, Generalizing for Public Declarations, Too, Decorator tradeoffs
supporting multiple instances, Supporting multiple instances
usage, Usage

class methods, Other Method Call Possibilities, Static and Class Methods, Using Static and Class Methods

counting instances, Counting Instances with Class Methods
counting per class, Counting instances per class with class methods
justification, Why the Special Methods?
using, Using Static and Class Methods

class properties, Increasing Levels of Magic

class statement, OOP: The Big Picture, The class Statement, Example, Class Statement Protocol

example, Example, Example
general form, General Form

classes, OOP: The Big Picture, Attribute Inheritance Search, Classes and Instances, OOP Is About Code Reuse

abstract superclasses, Abstract Superclasses, Python 2.6 and 3.0 Abstract Superclasses
as attributes of modules, Classes Are Attributes in Modules
built-in types, extending, Extending Built-in Types, Extending Types by Subclassing
embedding, Extending Types by Embedding
subclassing, Extending Types by Subclassing, Extending Types by Subclassing
class decorators, Class Decorators and Metaclasses
class hierarchies, Classes Are Customized by Inheritance
class instances, Instance Objects Are Concrete Items
class method calls, Class Method Calls
class methods (see class methods)
class statements, Coding Class Trees
class trees, Attribute Inheritance Search, Coding Class Trees, Coding Class Trees
classic classes, The “New-Style” Class Model
coding, A More Realistic Example, Updating Objects on a Shelve
behavior methods, Step 2: Adding Behavior Methods
class statement, The class Statement, Example
composition, delegation, and embedding, Other Ways to Combine Classes
constructors, customizing, Step 5: Customizing Constructors, Too, Other Ways to Combine Classes
databases, storing objects in, Step 7 (Final): Storing Objects in a Database, Updating Objects on a Shelve
docstrings, Documentation Strings Revisited
inheritance, Inheritance, Python 2.6 and 3.0 Abstract Superclasses
introspection, Step 6: Using Introspection Tools, Our Classes’ Final Form
making instances, Step 1: Making Instances, Using Code Two Ways
methods, Coding Methods, Methods, Other Method Call Possibilities
modules, versus, Classes Versus Modules
namespaces, Namespaces: The Whole Story, Namespace Links
OOP concepts embodied in, OOP Is Simpler Than You May Think
operator overloading, Step 3: Operator Overloading, Providing Print Displays
subclassing, Step 4: Customizing Behavior by Subclassing, OOP: The Big Idea
dependencies and function design, Function Design Concepts
dictionaries, versus, Classes Versus Dictionaries
distinctions of, Why Use Classes?
exception classes (see exception classes)
frameworks, OOP Is About Code Reuse
function decorators, Decorators and Metaclasses: Part 1, For More Details
gotchas, Class Gotchas
changing class attributes, Changing Class Attributes Can Have Side Effects
changing mutable class attributes, Changing Mutable Class Attributes Can Have Side Effects, Too
delegation-based classes (Python 3.0), Delegation-Based Classes in 3.0: __getattr__ and built-ins
methods, classes, and nested scopes (Python 2.2 and before), Methods, Classes, and Nested Scopes
multiple inheritance, Multiple Inheritance: Order Matters
overwrapping, “Overwrapping-itis”
inheritance, customization by, Classes Are Customized by Inheritance
instances, generation of, Classes Generate Multiple Instance Objects, A First Example
interception of Python operators, Classes Can Intercept Python Operators, Why Use Operator Overloading?
justification, Why Use Classes?
metaclasses, Type Model Changes, Metaclasses, Class Decorators and Metaclasses
as namespace objects, The World’s Simplest Python Class
naming conventions, Step 1: Making Instances
“new-style” classes, The “New-Style” Class Model, Metaclasses
changes, New-Style Class Changes, Scope of search order change
persistence and, Stream Processors Revisited
properties of, Class Objects Provide Default Behavior
simplest class, The World’s Simplest Python Class, Classes Versus Dictionaries
static and class methods, Static and Class Methods
subclasses and superclasses, Attribute Inheritance Search
user-defined classes, User-Defined Classes

classic division, Python Expression Operators, Division: Classic, Floor, and True

classmethod function, Using Static and Class Methods

classtree function, Namespace Links

close method, Using Files

closure function, Factory functions

code reuse

modules and, Why Use Modules?
OOP and, OOP Is About Code Reuse, OOP Is About Code Reuse

code reuse and code redundancy, Function Basics

codecs.open call (Python 2.6), Coding Unicode Strings in Python 2.6

cohesion, Function Design Concepts

collections (see lists)

colon (:), Common Coding Gotchas

command line (see interactive prompt)

command-line arguments, Using Command-Line Arguments with __name__

comments, A First Script, Python Syntax Rules, # Comments

companies using Python, Who Uses Python Today?

comparison methods, Comparisons: __lt__, __gt__, and Others

comparison operators, Comparisons: __lt__, __gt__, and Others

comparisons in Python 3.0, List method calls

compiled extensions, OK, but What’s the Downside?

complex numbers, Numeric Literals

component integration, Component Integration

composites, Other Ways to Combine Classes

composition, Why Use Classes?, OOP and Composition: “Has-a” Relationships, Stream Processors Revisited

stream processing with, Stream Processors Revisited

compound statements, What Python Adds, if Tests and Syntax Rules

general pattern, Python Syntax Rules

comprehension syntax, 3.0 Comprehension Syntax Summary, Extended Comprehension Syntax for Sets and Dictionaries

concatenation, Sequence Operations

constructor method, Classes Can Intercept Python Operators

__init__, Coding Constructors

constructors

coding, Coding Constructors
customizing, Step 5: Customizing Constructors, Too, Other Ways to Combine Classes

context managers, The Context Management Protocol

file and server connection closure, Closing Files and Server Connections

continue statement, break, continue, pass, and the Loop else, continue

control flow statements, Python Syntax Rules

conversionflag, Adding Specific Formatting

copy module, nested data structures, copying with, References Versus Copies

copying versus referencing of objects, References Versus Copies

core data types, Python’s Core Data Types, Step 2: Adding Behavior Methods

count method and tuples, Conversions, methods, and immutability

coupling, Function Design Concepts

CPython, CPython

cross-file module linking, Imports and Attributes

cross-file name changes, Cross-File Name Changes

curly braces { }, Python’s Core Data Types, Statement rule special cases

dictionaries and, Mapping Operations, Dictionaries
set comprehensions and, Set comprehensions in Python 3.0
sets and, Set literals in Python 3.0, Dictionary views and sets

CWD (current working directory), Imports outside packages

cyclic references, Objects Are Garbage-Collected

Cygwin, Where to Get Python

Cython, Other Execution Options

D

data attributes, Example

data hiding in modules, Data Hiding in Modules

data structures, Why Use Built-in Types?

database programming, Database Programming

databases, Future Directions

storing objects in, Step 7 (Final): Storing Objects in a Database, Updating Objects on a Shelve
pickles and shelves, Pickles and Shelves, Updating Objects on a Shelve

dbm module, Pickles and Shelves

debuggers, Development Tools for Larger Projects

debugging, Which Option Should I Use?

assert statement, The assert Statement
trapping constraints example, Example: Trapping Constraints (but Not Errors!)
outer try statements, using for, Debugging with Outer try Statements

decimal module, Decimal Type

decimal numeric literals, Numeric Literals

decimal numeric type, Other Core Types, Decimal Type, Decimal context manager

decoding and encoding, Character Encoding Schemes

decorators, What’s a Decorator?, Decorators Manage Functions and Classes, Too, Increasing Levels of Magic

call and instance management, Managing Calls and Instances
class decorators, Class Decorators, Supporting multiple instances
coding, Coding Class Decorators, Why Decorators? (Revisited)
decorator arguments, Decorator Arguments
versus function annotations, Decorator Arguments Versus Function Annotations
function decorators, Function Decorators, Supporting method decoration
coding, Coding Function Decorators, Adding Decorator Arguments
functions and classes, managing, Managing Functions and Classes, Decorators Manage Functions and Classes, Too, Managing Functions and Classes Directly
open issues, Open Issues, Implementation alternatives: __getattribute__ inserts, call stack inspection
private and public attributes, Example: “Private” and “Public” Attributes
justification, Why Decorators?
nesting, Decorator Nesting
type testing with, Other Applications: Type Testing (If You Insist!)
using and defining, Using and Defining Decorators

def statement, Python Scope Basics

default exception handler, Default Exception Handler

definitions, Definition, Definition

del statement, Type-Specific Operations

delegation, Other Ways to Combine Classes, Emulating Privacy for Instance Attributes: Part 1, OOP and Delegation: “Wrapper” Objects

descriptor protocol, Inserting Code to Run on Attribute Access

descriptors, Descriptors, How Properties and Descriptors Relate

descriptor methods, The Basics
method arguments, Descriptor method arguments
read-only descriptors, Read-only descriptors
__delete__ method, Read-only descriptors
__get__ method, Descriptor method arguments
__set__ method, Read-only descriptors
__slots__ implementation by, How Properties and Descriptors Relate

design patterns, OOP Is About Code Reuse

destructor method, Object Destruction: __del__

developer community, How Is Python Supported?

development tools, The Python Toolset, Development Tools for Larger Projects

Python toolset hierarchy, The Python Toolset

diamond pattern of multiple inheritance trees, Diamond Inheritance Change

dictionaries, Dictionaries, The has_key method is dead: long live in!

basic operations, Basic Dictionary Operations
changing in place, Changing Dictionaries In-Place
classes, versus, Classes Versus Dictionaries
coding of, Dictionaries
common literals and operations, Dictionaries
items method, More Dictionary Methods
languages table example, A Languages Table
pop method, More Dictionary Methods
Python 3.0 comparisons, Python 3.0 Dictionary Comparisons
Python 3.0, changes in, Dictionary Changes in Python 3.0
dictionary comprehensions, Dictionary comprehensions
dictionary magnitude comparisons, Dictionary magnitude comparisons no longer work
dictionary views, Dictionary views
dictionary views and sets, Dictionary views and sets
sorting dictionary keys, Sorting dictionary keys
use of in method instead of has_key, The has_key method is dead: long live in!
update method, More Dictionary Methods
usage notes, Dictionary Usage Notes
missing-key errors, avoiding, Avoiding missing-key errors
records, using as, Using dictionaries as “records”
simulating flexible lists, Using dictionaries to simulate flexible lists
sparse data structures, using for, Using dictionaries for sparse data structures
values method, More Dictionary Methods
ways of making dictionaries, Other Ways to Make Dictionaries

dictionary comprehensions, 3.0 Comprehension Syntax Summary

dictionary object type, Dictionaries, Missing Keys: if Tests

mapping operations, Mapping Operations
missing keys and if tests, Missing Keys: if Tests
nesting, Nesting Revisited
sorting keys and for loops, Sorting Keys: for Loops

dictionary view iterators, Dictionary View Iterators

dir function, Getting Help, The dir Function, Files Generate Namespaces, Namespace Dictionaries

mix-in classes, listing inherited attributes of, Listing inherited attributes with dir

direct or indirect recursion, Coding Alternatives

disutils, Advanced Module Selection Concepts, Development Tools for Larger Projects

division, Python Expression Operators, Division: Classic, Floor, and True, Why does truncation matter?

Python 2.6 and Python 3.0 compared, Variables and Basic Expressions

docstr.py, Documentation Strings Revisited

docstrings, Variables and Basic Expressions, Python Syntax Rules, Docstrings: __doc__, Documentation Strings Revisited, Development Tools for Larger Projects

built-in docstrings, Built-in docstrings
docstring standards, Docstring standards
user-defined docstrings, User-defined docstrings

doctest, Development Tools for Larger Projects

documentation, Python Documentation Sources, Published Books

dir function, The dir Function
docstrings (see docstrings)
hash-mark comments, # Comments
PyDoc, PyDoc: The help Function, PyDoc: HTML Reports
reference books, Published Books
standard manual set, The Standard Manual Set
web resources, Web Resources

DOM parsing, XML Parsing Tools

dotted path, Package Import Basics

double quotes (") and strings, Single- and Double-Quoted Strings Are the Same

dynamic typing, It’s Powerful, Python’s Core Data Types, The Dynamic Typing Interlude, Objects Are Garbage-Collected

garbage collection, Objects Are Garbage-Collected
objects, Variables, Objects, and References
versus variables, Types Live with Objects, Not Variables
polymorphism and, Dynamic Typing Is Everywhere
references, Variables, Objects, and References
shared references, Shared References, Shared References and Equality
variables, Variables, Objects, and References

E

Easter egg, Software Quality

EBCDIC encoding, Other Unicode Coding Techniques

Eclipse, Other IDEs

ElementTree package, XML Parsing Tools

elif (else if) clause, Missing Keys: if Tests, General Format

ellipses (...), pass

else clause, Missing Keys: if Tests, try Statement Clauses

(see also for statement; try statement; while statement)

Emacs, Text Editor Launch Options

embedded calls, Embedding Calls

embedding contrasted with inheritance, Other Ways to Combine Classes

empty strings, Strings

encapsulation, OOP Is About Code Reuse, Coding Methods

encoding and decoding, Character Encoding Schemes

encodings module, Character Encoding Schemes

end-of-line characters, Text and Binary Modes in 3.0

Enthought Python Distribution, Where to Get Python

enumerate function, Generating Both Offsets and Items: enumerate, Other Iteration Contexts

env program, Unix Executable Scripts (#!)

equality, testing for, Comparisons, Equality, and Truth

error checking

Python compared to C, Termination Actions

error handling, Exception Roles

etree package, XML Parsing Tools

eval function, Storing and parsing Python objects in files

event notification, Exception Roles

except clause, try Statement Clauses

(see also try statement)
empty clauses, try Statement Clauses, Catching Too Much: Avoid Empty except and Exception

Exception class, Built-in Exception Classes

built-in exceptions and system exit events, Catching Too Much: Avoid Empty except and Exception

exception classes, Exception Objects, Chapter Summary

advantages, Exception Objects
built-in exception classes, Built-in Exception Classes, Default Printing and State
categories, Built-in Exception Categories
default printing and state, Default Printing and State
hierarchies, Built-in Exception Classes
coding, Coding Exceptions Classes
custom data and behavior, Custom Data and Behavior, Providing Exception Methods
providing exception details, Providing Exception Details
providing exception methods, Providing Exception Methods
custom print displays, Custom Print Displays
defining handler methods, Providing Exception Methods
exception hierarchies, Class-Based Exceptions
justification, Why Exception Hierarchies?, Why Exception Hierarchies?

exceptions, Exception Basics

assert statement, The assert Statement
trapping constraints example, Example: Trapping Constraints (but Not Errors!)
catching built-in exceptions example, Example: Catching Built-in Exceptions
catching exceptions, Catching Exceptions
class-based exceptions, Class-Based Exceptions
(see also exception classes)
for closing files and server connections, Closing Files and Server Connections
default behavior, Example: Default Behavior
default exception handlers, Default Exception Handler
design tips and gotchas, Exception Design Tips and Gotchas, Catching Too Little: Use Class-Based Categories
handler specificity and class-based categories, Catching Too Little: Use Class-Based Categories
limiting handler generality, Catching Too Much: Avoid Empty except and Exception
wrappers, What Should Be Wrapped
exception handlers, Why Use Exceptions?
nested exception handlers, Nesting Exception Handlers, Example: Syntactic Nesting
in-process testing with, Running In-Process Tests
justification, Why Use Exceptions?
nonerror exceptions, Exceptions Aren’t Always Errors, Functions Can Signal Conditions with raise
user-defined exceptions, Functions Can Signal Conditions with raise
purposes, Exception Roles
raise statement, The raise Statement, Python 3.0 Exception Chaining: raise from
raising exceptions, Raising Exceptions
string exceptions, deprecation of, String Exceptions Are Right Out!
termination actions, Termination Actions
try statement (see try statement)
typical uses for, Exception Idioms, More on sys.exc_info
user-defined exceptions, User-Defined Exceptions
with/as statement, with/as Context Managers, The Context Management Protocol
context management protocol, The Context Management Protocol
usage, Basic Usage

exec function, Using exec to Run Module Files

loading modules from a string, Importing Modules by Name String

exec statement (Python 2.6), Python’s Statements

executable files

creating with Python, Frozen Binaries
Unix path, defining in comment, Unix Executable Scripts (#!)

executable scripts, Unix Executable Scripts (#!)

execution optimization tools, Execution Optimization Tools

exercises, This Book’s Style and Structure

Part I, Test Your Knowledge: Part I Exercises
Part II, Test Your Knowledge: Part II Exercises
Part III, Test Your Knowledge: Part III Exercises
Part IV, Test Your Knowledge: Part IV Exercises
Part V, Test Your Knowledge: Part V Exercises
Part VI, Test Your Knowledge: Part VI Exercises
Part VII, Test Your Knowledge: Part VII Exercises

expression operators, Built-in Numeric Tools

table of, including precedence, Python Expression Operators
versions 3.0 and 2.x differences, Python Expression Operators

expression statements, Expression Statements

in-place changes, Expression Statements and In-Place Changes

expressions, Introducing Python Object Types, Python Expression Operators

mixing operators, Mixed types are converted up
parentheses and, Parentheses group subexpressions

extend method, List method calls

extended slicing, Extended slicing: the third limit and slice objects

extensions in Python versions 2.6 and 3.0, Specific Language Extensions in 2.6 and 3.0

F

factories, Classes Are Objects: Generic Object Factories, Why Factories?

justification, Why Factories?

factoring of code, Coding Methods

factory design pattern, Classes Are Objects: Generic Object Factories

factory functions, Factory functions

false and true values, The Meaning of True and False in Python

fieldname, Adding Specific Formatting

file execution, The Programmer’s View

file icon clicks, Clicking File Icons, Other Icon-Click Limitations

limitations, Other Icon-Click Limitations

file input/output, Python 3.0, Text and Binary Files

file iterators, The Iteration Protocol: File Iterators

file object methods and printing operations, Print Operations

file object type, Files

files, Tuples, Files, and Everything Else, Files, Other File Tools

advanced file methods, Other File Tools
common operations, Files
examples of usage, Files in Action, File context managers
file context managers, File context managers
packed binary data, storing and parsing in files, Storing and parsing packed binary data in files
storing and parsing of Python objects, Storing and parsing Python objects in files
text and binary files, Python 3.0, Text and binary files in Python 3.0
file iterators, Files in Action
mode string argument for opening, Text and Binary Files
opening, Opening Files
pickle, Storing native Python objects with pickle
using, Using Files

filter, Other Iteration Contexts

filter function, Functional Programming Tools: filter and reduce

filter iterator, The map, zip, and filter Iterators

finally clause, try Statement Clauses, The try/finally Statement

(see also try statement)

find method, Type-Specific Methods

fixed-precision floating-point values, Decimal Type

floating point numbers, Numeric Literals

floor division, Python Expression Operators, Division: Classic, Floor, and True

flush method, Using Files

for loop

iterator, as an example of, Iterators: A First Look
line-by-line iteration with __next__ method, The Iteration Protocol: File Iterators
versus while and range, Common Coding Gotchas

for statement, while and for Loops, for Loops, Nested for loops

examples, Examples
extended sequence unpacking in, Python 3.0 extended sequence assignment in for loops
format, General Format
nested for loops, Nested for loops
tuple assignment in, Tuple assignment in for loops

format function, Adding Specific Formatting

format method, The Basics, Adding Specific Formatting

formats.py, Using Command-Line Arguments with __name__

formatspec, Adding Specific Formatting

formatting, Type-Specific Methods

fraction number object type, Other Core Types

Fraction numeric type, Fraction Type, Conversions and mixed types

conversions, Conversions and mixed types

frameworks, OOP Is About Code Reuse

freeze, Frozen Binaries

from clause (raise statement), Python 3.0 Exception Chaining: raise from

from statement, Module Imports and Reloads, The Grander Module Story: Attributes, The from Statement, The from * Statement

as assignment, import and from Are Assignments
equivalence to import, import and from Equivalence
from imports and reload statement, reload May Not Impact from Imports
interactive testing, reload, from, and Interactive Testing
import statement, versus, Modules and namespaces
name copying without linking, from Copies Names but Doesn’t Link
pitfalls, Potential Pitfalls of the from Statement, When import is required
corruption of namespaces, Potential Pitfalls of the from Statement
reload statement, when used with, Potential Pitfalls of the from Statement
when import is required, When import is required
variables and, from * Can Obscure the Meaning of Variables
_ (underscore) prefix and __all__ variable, Minimizing from * Damage: _X and __all__

from __future__ statement, Relative Import Basics

from_float method, Conversions and mixed types

frozen binaries, Frozen Binaries, Frozen Binary Executables, Development Tools for Larger Projects

frozenset built-in call, Immutable constraints and frozen sets

function argument-matching forms, Matching Syntax

function attributes, State with function attributes, Function Attributes

function calls, Class Method Calls

function decorators, Decorators and Metaclasses: Part 1, For More Details, Managing Calls and Instances, Function Decorators

basics, Function Decorator Basics
coding, Coding Function Decorators, Why Decorators? (Revisited)
adding arguments, Adding Decorator Arguments, Adding Decorator Arguments
decorating class methods, Class Blunders I: Decorating Class Methods, Using descriptors to decorate methods
state information retention, State Information Retention Options, Function attributes
timing calls, Timing Calls, Timing Calls
tracing calls, Tracing Calls
example, A First Function Decorator Example
function arguments, validating, Example: Validating Function Arguments, Other Applications: Type Testing (If You Insist!)
generalizing for keywords and defaults, Generalizing for Keywords and Defaults, Too
implementation details, Implementation Details
open issues, Open Issues
range-tester for positional arguments, A Basic Range-Testing Decorator for Positional Arguments
implementation, Implementation
properties of managed attributes, coding with, Coding Properties with Decorators
supporting method decoration, Supporting method decoration
usage, Usage

function introspection, Function introspection

functional programming, Functional Programming Tools: filter and reduce

functions, Function Basics, def Executes at Runtime

attributes and annotations, Function Objects: Attributes and Annotations, Function Annotations in 3.0
calls, Calls, Calls
coding, Coding Functions, def Executes at Runtime
definitions, Definition, Definition
dependencies and function design, Function Design Concepts
design concepts, Function Design Concepts
example, definitions and calls, A First Example: Definitions and Calls
example, intersecting sequences, A Second Example: Intersecting Sequences, Local Variables
local variables, Local Variables
function annotations (Python 3.0), Function Annotations in 3.0
function attributes, Function Attributes
function instrospection, Function Introspection
function related statements and expressions, Function Basics
global statement (see global statement)
gotchas, Function Gotchas, Enclosing Scope Loop Variables
default arguments and mutable objects, Defaults and Mutable Objects
enclosing scope loop variables, Enclosing Scope Loop Variables
functions without returns, Functions Without returns
static detection of local names, Local Names Are Detected Statically
indirect function calls, Indirect Function Calls
lambda expression (see lambda expression)
local scope, Scope Rules
mapping over sequences, Mapping Functions over Sequences: map
nonlocal statement (see nonlocal statement)
parentheses and, Common Coding Gotchas
polymorphism, Polymorphism in Python, Polymorphism Revisited
purpose of, Why Use Functions?
recursive functions, Recursive Functions, Handling Arbitrary Structures
arbitrary structures, handling, Handling Arbitrary Structures
coding alternatives, Coding Alternatives
loop statements, versus, Loop Statements Versus Recursion
summation, Summation with Recursion
return statement (see return statement)
simple functions, Static Methods in 2.6 and 3.0
yield statement (see yield statement)

G

garbage collection, Nesting Revisited, Objects Are Garbage-Collected

generator expressions, Iterators Revisited: Generators, Generator Expressions: Iterators Meet Comprehensions, Listing attributes per object in class trees

generator functions, Iterators Revisited: Generators, Value Generation in Built-in Types and Classes

examples, Generator functions in action
generator expressions, versus, Generator Functions Versus Generator Expressions
iteration protocol and, Iteration protocol integration
iteration tools
coding a map(func, ...), Coding your own map(func, ...)
coding zip(...) and map(None, ...), Coding your own zip(...) and map(None, ...)
emulating zip and map functions, Emulating zip and map with Iteration Tools, Coding your own zip(...) and map(None, ...)
one-shot iterations, Coding your own zip(...) and map(None, ...)
send method and __next__, Extended generator function protocol: send versus next
state suspension, State suspension
value generation in built-in types and classes, Value Generation in Built-in Types and Classes

generator objects, Generating Both Offsets and Items: enumerate

generators, Comprehensions, Generators Are Single-Iterator Objects

get method, Missing Keys: if Tests

getrefcount function, Shared References and Equality

global scope, Scope Rules

access without the global statement, Other Ways to Access Globals

global statement, Scope Rules, The global Statement, Other Ways to Access Globals

minimize cross-file changes, Minimize Cross-File Changes
minimize global variables, Minimize Global Variables

Google’s Unladen Swallow project, Future Possibilities?

GUIs (Graphical User Interfaces), GUIs, Future Directions

H

handlers, Catching Exceptions

“has-a” relationships, OOP and Composition: “Has-a” Relationships

hash bang (#!), Unix Executable Scripts (#!)

hash character (#), A First Script

hash tables, Dictionaries

hash-mark comments, # Comments

hashes, Dictionaries

has_key method (Python 2.x), Missing Keys: if Tests

help function, Getting Help, PyDoc: The help Function, Development Tools for Larger Projects

helper functions, The Downside of “Helper” Functions

hexadecimal numeric literals, Numeric Literals

home directory, The Module Search Path

I

IDEs, Other IDEs, Development Tools for Larger Projects

IDLE (see IDLE user interface)

IDLE user interface, The IDLE User Interface, Advanced IDLE Tools

getting support on Linux, Python Environment Variables
IDLE debugger, Advanced IDLE Tools
source code, creation and editing in, IDLE Basics
startup in Windows and Unix-like systems, IDLE Basics
usage and pitfalls, Using IDLE

if clause, Comprehensions

if statement, Missing Keys: if Tests, if Tests and Syntax Rules, Multiway Branching

examples, Basic Examples
format, General Format
multiway branching, Multiway Branching

if/else ternary expression, The if/else Ternary Expression

immutability, Immutability

immutable objects, Immutable Types Can’t Be Changed In-Place

implementation of shared services and data, Why Use Modules?

implementation-related types, Python’s Core Data Types

import hooks, Advanced Module Selection Concepts

import statement, Module Imports and Reloads, Imports and Attributes, Module File Selection, The import Statement

.py file extension and, Using Command Lines and Files
as assignment, import and from Are Assignments
cross-file name changes, Cross-File Name Changes
enabling new language features, Enabling Future Language Features
from statement, equivalence to, import and from Equivalence
from statement, versus, Modules and namespaces
usage notes, import and reload Usage Notes

imports, How Imports Work, Imports Happen Only Once

in expressions, Multiway Branching

in membership expression, Missing Keys: if Tests

in-place addition, In-Place Addition

in-place change operations, Common Coding Gotchas

incremental prototyping, Testing As You Go

indentation, End of indentation is end of block, Why Indentation Syntax?, Python Syntax Rules, Common Coding Gotchas

rules, Block Delimiters: Indentation Rules
tabs versus spaces, Avoid mixing tabs and spaces: New error checking in 3.0

index method, List method calls

and tuples, Conversions, methods, and immutability

indexing, Indexing and Slicing

indexing expressions, Sequence Operations

indirect function calls, Indirect Function Calls

infinite loops, Examples

inheritance, Why Use Classes?, Attribute Inheritance Search, Classes Are Customized by Inheritance, Classes Are Attributes in Modules, Inheritance, Python 2.6 and 3.0 Abstract Superclasses

abstract superclasses, Abstract Superclasses, Python 2.6 and 3.0 Abstract Superclasses
attribute inheritance, key ideas of, Classes Are Customized by Inheritance
attribute trees, Attribute Tree Construction
class interface techniques, Class Interface Techniques
real-world relationships, modeling with, OOP and Inheritance: “Is-a” Relationships
simplicity of inheritance model, The World’s Simplest Python Class
specializing inherited methods, Specializing Inherited Methods

input function, The input Trick

insert method, Type-Specific Operations, List method calls

installing Python, Introducing the Python Interpreter

instance methods, Using Static and Class Methods

instances, Attribute Inheritance Search, Classes and Instances, Classes Generate Multiple Instance Objects, Instance Objects Are Concrete Items, A More Realistic Example

making instances, Step 1: Making Instances, Using Code Two Ways
coding constructors, Coding Constructors
incremental testing, Testing As You Go
test code, Using Code Two Ways
as namespace objects, The World’s Simplest Python Class

int, String Conversion Tools

int function, Storing and parsing Python objects in files

integer division, Python 2.6 versus 3.0, Variables and Basic Expressions

integers, Numeric Literals

Python 3.0, Numeric Literals

integrated development environments (see IDEs)

interactive loops, A Quick Example: Interactive Loops, Nesting Code Three Levels Deep

math operations on user input, Doing Math on User Inputs
nesting code three levels deep, Nesting Code Three Levels Deep
simple example, A Simple Interactive Loop
testing inputs, Handling Errors by Testing Inputs
try statements, handling errors with, Handling Errors with try Statements

interactive prompt, The Interactive Prompt, Entering multiline statements

exiting a session, Running Code Interactively
experimenting with code, Experimenting
files, running from, Running Files with Command Lines
multiline statements, entering, Entering multiline statements
testing code, Testing
tips for using, Using the Interactive Prompt

Internet scripting, Internet Scripting