A note on the digital index A link in an index entry is displayed as the section title in which that entry appears. Because some sections have multiple index markers, it is not unusual for an entry to have several links to the same section. Clicking on any link will take you directly to the place in the text in which the marker appears.
Symbols % (formatting operator), String Formatting Expressions , Adding Specific Formatting = and == (equality operators), Comparisons, Equality, and Truth * (repetition) operator, Basic List Operations @ symbol, Function Decorator Basics (backslash)
escape sequences, Other Ways to Code Strings (backslash), Statement rule special cases , A Few Special Cases & (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 1{ } (curly braces) dictionaries and, Mapping Operations { } (curly braces), Python’s Core Data Types , Python Expression Operators , Statement rule special cases dictionaries and, 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 , 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 + (concatenation)
operator, Basic List Operations + (plus operator), Python Expression Operators “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__ __all__ variable, Package __init__.py Files 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 all, any, Other Iteration Contexts , Coding your own zip(...) and map(None, ...) 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 , The if/else Ternary Expression 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 , 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 classtools.py, A Generic Display Tool 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, Using dictionaries as “records” , 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, The “New-Style” Class Model , 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 distutils, Advanced Module Selection Concepts disutils, 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 eggs, Development Tools for Larger Projects 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 , try Statement Clauses (see also for statement; try statement; while statement) Emacs, Other IDEs , 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 Built-in Type Iterators , Other Iteration Contexts env program, Unix Executable Scripts (#!) environment variables, Python Environment Variables 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 , try Statement Clauses (see also try statement) empty clauses, try Statement Clauses , Catching Too Much: Avoid Empty except and Exception Exception class, User-Defined Exceptions , try Statement Clauses , Exceptions: Back to the Future , 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 , 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 , 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 getattr, Modules Are Objects: Metaprograms , Other Ways to Combine Classes 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 as keyword, from Versus import with Packages , The as Extension for import and from 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 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 interpreters, Introducing the Python Interpreter introspection, Modules Are Objects: Metaprograms introspection attributes, Increasing Levels of Magic IronPython, IronPython , Where to Get Python is operator, Comparisons, Equality, and Truth “is-a”
relationships, OOP and Inheritance: “Is-a” Relationships isinstance, How to Break Your Code’s Flexibility , Type Objects , Handling Arbitrary Structures , Right-Side and In-Place Addition: __radd__ and __iadd__ is_integer method, Built-in Numeric Tools items method, More Dictionary Methods , Dictionary View Iterators iter function, Manual Iteration: iter and next iteration, Iterations and Comprehensions, Part 2 built-in tools for, Other Iteration Contexts manual iteration, Manual Iteration: iter and next iteration protocol, Iteration and Optimization , Iterations and Comprehensions, Part 1 , The Iteration Protocol: File Iterators , Iteration protocol integration iterators, Iterators: A First Look –Other Built-in Type Iterators additional built-in iterators, Other Built-in Type Iterators file iterators, The Iteration Protocol: File Iterators filter, The map, zip, and filter Iterators generator functions (see generator functions) map, The map, zip, and filter Iterators in Python 3.0, New Iterables in Python 3.0 –Dictionary View Iterators range, The range Iterator support for multiple iterators, Multiple Versus Single Iterators range function, Counter Loops: while and range timing iteration alternatives, Timing Iteration Alternatives –Other Suggestions other suggestions, Other Suggestions time module, Timing Module time module alternatives, Timing Module Alternatives timing results, Timing Results timing script, Timing Script zip, The map, zip, and filter Iterators iters.py, User-Defined Iterators L lambda expression, Anonymous Functions: lambda –Nested lambdas and Scopes basics, lambda Basics defining inline callback functions in
tkinter, Nested lambdas and Scopes justification for, Why Use lambda? nested lambdas and scopes, Nested lambdas and Scopes potential for code obfuscation, How (Not) to Obfuscate Your Python Code lambdas and nested scopes, Nested scopes and lambdas Latin-1 character encoding, Character Encoding Schemes LEGB rule, Name Resolution: The LEGB Rule len function, Sequence Operations lexical scoping, Python Scope Basics Linux Python command line, starting, The Interactive Prompt list comprehension expressions, Comprehensions list comprehensions, Iterations and Comprehensions, Part 1 , List Comprehensions: A First Look –Extended List Comprehension Syntax , List Comprehensions Revisited: Functional Tools basics, List Comprehension Basics best uses of, Comprehending List Comprehensions extended syntax, Extended List Comprehension Syntax files, using on, Using List Comprehensions on Files map function and, Comprehending List Comprehensions map function, versus, List Comprehensions Versus map matrixes and, List Comprehensions and Matrixes tests and nested loops, adding, Adding Tests and Nested Loops: filter list object type, Lists –Comprehensions bounds checking, Bounds Checking nesting, Nesting type specific operations, Type-Specific Operations list-unpacking assignment statements, Assignment Statement Forms lister.py, Listing instance attributes with __dict__ ListInstance class, Listing instance attributes with __dict__ –Listing instance attributes with __dict__ lists, Lists basic operations, Basic List Operations changing in place, Changing Lists In-Place –Other common list operations deleting items or sections in place, Other common list operations index and slice assignments, Index and slice assignments list method calls, List method calls –List method calls coding of lists, Lists common literals and operations, Lists indexing, slicing, and matrixes, Indexing, Slicing, and Matrixes iteration and comprehensions, List Iteration and Comprehensions literals, Python’s Core Data Types local scope, Scope Rules local variables, Local Variables lock (thread), Basic Usage long integers (Python 2.6), Numeric Literals loop else block, break, continue, pass, and the Loop else loop statement versus recursive functions, Loop Statements Versus Recursion loops, while and for Loops –Generating Both Offsets and Items: enumerate break, continue, pass, and loop else clause, break, continue, pass, and the Loop else coding techniques, Loop Coding Techniques –Generating Both Offsets and Items: enumerate counter loops with while and range, Counter Loops: while and range for statement, for Loops –Nested for loops general format, General Loop Format generation of offsets and items, Generating Both Offsets and Items: enumerate interactive loops (see interactive loops) loop else clause, Loop else nonexhaustive traversals with range and
slices, Nonexhaustive Traversals: range and Slices parallel traversals with zip and map, Parallel Traversals: zip and map range function lists, changing with, Changing Lists: range while statement, while Loops M Mac OS X Python command line, starting, The Interactive Prompt makedb.py, Storing Objects on a Shelve Database managed attributes, Managed Attributes –Coding Properties with Decorators attribute validations example, Example: Attribute Validations –Using __getattribute__ to Validate descriptors validation, Using Descriptors to Validate properties validation, Using Properties to Validate __getattribute__, validation with, Using __getattribute__ to Validate __getattr__, validation with, Using __getattr__ to Validate coding to run on attribute access, Inserting Code to Run on Attribute Access comparison of management techniques, Management Techniques Compared descriptors, Descriptors –How Properties and Descriptors Relate computed attributes, Computed Attributes descriptor methods, The Basics example, A First Example method arguments, Descriptor method arguments properties, relation to, How Properties and Descriptors Relate read-only descriptors, Read-only descriptors state information, using in, Using State Information in Descriptors justification, Why Manage Attributes? –Inserting Code to Run on Attribute Access properties, Properties –Coding Properties with Decorators computed attributes, Computed Attributes decorators, coding with, Coding Properties with Decorators first example, A First Example new-style object derivation requirement, A First Example __getattr__ and __getattribute__, __getattr__ and __getattribute__ –Delegation-Based Managers Revisited avoiding loops, Avoiding loops in attribute interception methods comparison, __getattr__ and __getattribute__ Compared computed attributes, Computed Attributes delegation, The Basics example, A First Example interception of built-in attributes, Intercepting Built-in Operation Attributes –Delegation-Based Managers Revisited Manager class, A More Realistic Example , Coding Subclasses manager functions, The Downside of “Helper” Functions manual iteration, Manual Iteration: iter and next manynames.py, The “Zen” of Python Namespaces: Assignments Classify
Names map function, List Iteration and Comprehensions , map equivalence in Python 2.6 , Mapping Functions over Sequences: map lambda expressions and, Mapping Functions over Sequences: map list comprehensions and, Comprehending List Comprehensions list comprehensions, versus, List Comprehensions Versus map map iterator, The map, zip, and filter Iterators matching algorithm, Matching algorithm math module, Numbers example functions, Other Built-in Numeric Tools mathematical functions, Built-in Numeric Tools max and min functions, Other Iteration Contexts mergdexc.py, Unified try Example metaclass model, The Metaclass Model –Class Statement Protocol , Classes Are Instances of type (see also metaclasses) class statement protocol, Class Statement Protocol classes are instances of type, Classes Are Instances of type metaclasses are subclasses of type, Metaclasses Are Subclasses of Type metaclasses, Type Model Changes , Metaclasses , Class Decorators and Metaclasses , Metaclasses –The Downside of “Helper” Functions , The Metaclass Model (see also metaclass model) adding methods to classes example, Example: Adding Methods to Classes –Managing instances instead of classes manual augmentation, Manual Augmentation metaclass-based augmentation, Metaclass-Based Augmentation applying decorators to methods example, Example: Applying Decorators to Methods –Metaclasses Versus Class Decorators: Round 3 manual tracing, Tracing with Decoration Manually tracing with metaclasses and decorators, Tracing with Metaclasses and Decorators with any decorators, Applying Any Decorator to Methods class decorators, compared to, Metaclasses Versus Class Decorators: Round 2 –Managing instances instead of classes , Metaclasses Versus Class Decorators: Round 3 decorator-based augmentation, Decorator-based augmentation managing instances instead of classes, Managing instances instead of classes class decorators, compared with, Metaclasses Versus Class Decorators: Round 1 coding, Coding Metaclasses –Instances Versus Inheritance basic metaclass, A Basic Metaclass customizing construction and initialization, Customizing Construction and Initialization factory functions, using, Using simple factory functions instances versus inheritance, Instances Versus Inheritance overloading class creation calls with
classes, Overloading class creation calls with normal
classes overloading class creation calls with
metaclasses, Overloading class creation calls with metaclasses declaration, Declaring Metaclasses issues around use, To Metaclass or Not to Metaclass potential roles, To Metaclass or Not to Metaclass metafunctions, Function Decorator Basics metaprograms, Modules Are Objects: Metaprograms –Modules Are Objects: Metaprograms method call expression, String Methods methods, Type-Specific Methods , Getting Help , List method calls , The World’s Simplest Python Class , Coding Methods , Methods –Other Method Call Possibilities augmenting methods, Augmenting Methods: The Bad Way bound and unbound methods, Methods Are Objects: Bound or Unbound –Bound Methods and Other Callable Objects bound methods, Function Interfaces and Callback-Based Code calls to methods, Method Example –Other Method Call Possibilities class methods, Other Method Call Possibilities coding methods, Coding Methods comparison methods, Comparisons: __lt__, __gt__, and Others destructor method, Object Destruction: __del__ example, Method Example static methods, Other Method Call Possibilities , Static and Class Methods (see also static methods) superclass constructors, calling, Calling Superclass Constructors min and max functions, Other Built-in Numeric Tools mins.py, Full Credit mix-in classes, Multiple Inheritance: “Mix-in” Classes coding, Coding Mix-in Display Classes –Listing attributes per object in class trees instance attributes, listing, Listing instance attributes with __dict__ listing inherited attributes, Listing inherited attributes with dir listing object attributes in class trees, Listing attributes per object in class trees module packages, Module Packages package imports, Package Import Basics –A Tale of Three Systems import example, Package Import Example –from Versus import with Packages justification, Why Use Package Imports? –A Tale of Three Systems packages and search path settings, Packages and Search Path Settings __inti__.py, Package __init__.py Files package relative imports (see package relative imports) modules, System Command Lines and Files , Module Imports and Reloads , Introducing Python Object Types , Modules: The Big Picture as extension for import and from, The as Extension for import and from attributes, The Grander Module Story: Attributes , How to Structure a Program , Module Creation classes, as attributes of, Classes Are Attributes in Modules classes, versus, Classes Versus Modules creating, Module Creation data hiding in, Data Hiding in Modules design concepts, Module Design Concepts exec, running module files with, Using exec to Run Module Files from statement, The from Statement , The from * Statement future language features, enabling, Enabling Future Language Features global scope, Scope Rules gotchas, Module Gotchas –Recursive from Imports May Not Work from imports and reload, reload May Not Impact from Imports from statement, from Copies Names but Doesn’t Link from statement and variables, from * Can Obscure the Meaning of Variables recursive import failures, Recursive from Imports May Not Work statement order in top-level code, Statement Order Matters in Top-Level Code import statement, The import Statement importing byte code compilation if required, 2. Compile It (Maybe) running, 3. Run It importing by name string, Importing Modules by Name String importing of modules, How Imports Work –3. Run It locating, 1. Find It imports and reloads, Module Imports and Reloads –import and reload Usage Notes metaprograms, Modules Are Objects: Metaprograms –Modules Are Objects: Metaprograms mixed-usage modes, Mixed Usage Modes: __name__ and __main__ –Using Command-Line Arguments with __name__ module extensions, Module Creation module namespaces, Module Namespaces –Namespace Nesting attribute name qualification, Attribute Name Qualification generation from files, Files Generate Namespaces imports versus scopes, Imports Versus Scopes namespace nesting, Namespace Nesting module search path, import and reload Usage Notes , 1. Find It , The Module Search Path –Advanced Module Selection Concepts advanced module selection concepts, Advanced Module Selection Concepts module file selection, Module File Selection search path configuration, Configuring the Search Path search path variations, Search Path Variations sys.path list, The sys.path List third-party extensions, Advanced Module Selection Concepts module search path, changing, Changing the Module Search Path namespaces, Modules and namespaces , Why Use Modules? naming conventions, Step 1: Making Instances naming of, Module Creation program structure and, Python Program Architecture reloading modules, Reloading Modules –reload Example example, reload Example roles of, Why Use Modules? scope, Files Generate Namespaces standard library, Standard Library Modules transitive module reloads, Transitive Module Reloads –Transitive Module Reloads __name__ attribute, Mixed Usage Modes: __name__ and __main__ –Using Command-Line Arguments with __name__ command-line arguments with, Using Command-Line Arguments with __name__ unit tests, Unit Tests with __name__ Monty Python’s Flying Circus, It’s Named After Monty Python multiline statements, Statement Delimiters: Lines and Continuations multiple inheritance, Coding Class Trees , Multiple Inheritance: “Mix-in” Classes –Listing attributes per object in class trees diamond pattern inheritance trees, Diamond Inheritance Change mix-in classes (see mix-in classes) multiway branching, Multiway Branching mutable objects, Lists , Step 2: Adding Behavior Methods mutables in assignments, Common Coding Gotchas mybooks.xml, XML Parsing Tools mydir.py, Modules Are Objects: Metaprograms myfile.py, The Grander Module Story: Attributes N name attribute, User-Defined Classes name mangling, Pseudoprivate Class Attributes –Why Use Pseudoprivate Attributes? namespace objects, Testing As You Go namespaces, The Grander Module Story: Attributes , Modules and namespaces , Python Scope Basics , Why Use Modules? , Classes and Instances , Namespaces: The Whole Story –Namespace Links attribute names, Attribute Names: Object Namespaces name assignment, The “Zen” of Python Namespaces: Assignments Classify
Names –The “Zen” of Python Namespaces: Assignments Classify
Names namespace dictionaries, Namespace Dictionaries –Namespace Dictionaries namespace links, Namespace Links simple names, Simple Names: Global Unless Assigned negative offsets, Indexing and Slicing nested scopes, Scopes and Nested Functions –Arbitrary scope nesting abitrary nesting, Arbitrary scope nesting examples, Nested Scope Examples factory functions, Factory functions lambdas and, Nested scopes and lambdas nester.py, Methods, Classes, and Nested Scopes .NET and
IronPython, IronPython NetBeans, Other IDEs “new-style”
classes, The “New-Style” Class Model –Class Properties changes, New-Style Class Changes –Scope of search order change class extensions, New-Style Class Extensions –Metaclasses class properties, Class Properties –Class Properties instance slots, Instance Slots –Multiple __slot__ lists in superclasses metaclasses, Metaclasses multiple __slot__ lists in superclasses, Multiple __slot__ lists in superclasses slots and generic code, Slots and generic code __getattribute__ method, __getattribute__ and Descriptors diamond inheritance change, Diamond Inheritance Change –Scope of search order change example, Diamond inheritance example explicit conflict resolution, Explicit conflict resolution scope of search order, Scope of search order change type model changes, Type Model Changes –All objects derive from “object” object type objects, All objects derive from “object” type testing implications, Implications for type testing next function, Manual Iteration: iter and next __next__ method, The Iteration Protocol: File Iterators non-ASCII text, coding, encoding and decoding, Coding Non-ASCII Text –Encoding and Decoding Non-ASCII text None object, The None object nonlocal statement, Scope Rules , The nonlocal Statement –State with function attributes absence from Python 2.6, Python’s Statements basics, nonlocal Basics examples, nonlocal in Action boundary cases, Boundary cases justification for, Why nonlocal? –State with function attributes Python 2.6 alternatives, Shared state with globals normal integers (Python 2.6), Numeric Literals number object type, Numbers number operations, Numbers in Action –Other Built-in Numeric Tools bitwise operations, Bitwise Operations comparisons, Comparisons: Normal and Chained chained comparisons, Comparisons: Normal and Chained complex numbers, Complex Numbers division, Division: Classic, Floor, and True –Why does truncation matter? integer precision, Integer Precision math module functions, Other Built-in Numeric Tools notation, hexadecimal, octal, and binary, Hexadecimal, Octal, and Binary Notation numeric display formats, Numeric Display Formats variables and basic expressions, Variables and Basic Expressions –Variables and Basic Expressions numeric display formats, Numeric Display Formats numeric extensions, Numeric Extensions numeric object type, Numeric Type Basics –Built-in Numeric Tools built-in numeric tools, Built-in Numeric Tools complexity ranking, Mixed types are converted up expression operators and precedence, Python Expression Operators numeric literals, Numeric Literals operator overloading and polymorphism, Preview: Operator overloading and polymorphism some noncore types, Other Numeric Types –Booleans Booleans, Booleans decimal type, Decimal Type –Decimal context manager fraction types, Fraction Type –Conversions and mixed types sets, Sets –Why sets? numeric precision, setting globally, Setting precision globally numeric programming, Numeric and Scientific Programming NumPy numeric programming extension, OK, but What’s the Downside? , Numeric and Scientific Programming , Numeric Extensions O object embedding, Other Ways to Combine Classes object persistence, Step 7 (Final): Storing Objects in a Database object type categories, General Type Categories mutable versus immutable types, Mutable Types Can Be Changed In-Place shared operation sets, Types Share Operation Sets by Categories object types, And Everything Else built-in object types (see built-in object types) object-oriented programming, It’s Object-Oriented object-oriented scripting language, Is Python a “Scripting Language”? object.attr expression, Inheritance object.attribute expression, Attribute Inheritance Search object.attribute notation, Imports and Attributes objects, Introducing Python Object Types , Numeric Types , Variables, Objects, and References comparisons, equality, and truth, Comparisons, Equality, and Truth compound object types, Object Flexibility copying versus referencing, Shared References and In-Place Changes databases, storing objects in, Step 7 (Final): Storing Objects in a Database dynamic typing and, Variables, Objects, and References iterable objects, Iterators: A First Look nonbuilt-in object types, Other Types in Python object classifications for built-in
types, Type Categories Revisited references versus copies, References Versus Copies truth and falsity, The Meaning of True and False in Python bool type, The bool type None object, The None object type hierarchies, Python’s Type Hierarchies type object type, Type Objects octal numeric literals, Numeric Literals OOP (object-oriented programming), OOP from 30,000 Feet –OOP Is About Code Reuse as exemplified by coding of classes, OOP: The Big Idea attribute inheritance search, Attribute Inheritance Search class method calls, Class Method Calls classes, Attribute Inheritance Search , Classes and Instances , Classes Generate Multiple Instance Objects class trees, Coding Class Trees –Coding Class Trees customization by inheritance, Classes Are Customized by Inheritance –Classes Are Attributes in Modules code reuse, OOP Is About Code Reuse –OOP Is About Code Reuse design issues, Designing with Classes bound and unbound methods, Methods Are Objects: Bound or Unbound –Bound Methods and Other Callable Objects composition, OOP and Composition: “Has-a” Relationships –Stream Processors Revisited delegation and wrapper classes, OOP and Delegation: “Wrapper” Objects generic object factories, Classes Are Objects: Generic Object Factories inheritance, OOP and Inheritance: “Is-a” Relationships multiple inheritance, Multiple Inheritance: “Mix-in” Classes –Listing attributes per object in class trees polymorphism, Overloading by Call Signatures (or Not) pseudoprivate class attributes, Pseudoprivate Class Attributes –Why Use Pseudoprivate Attributes? design patterns, OOP Is About Code Reuse important concepts, OOP Is Simpler Than You May Think instances, Attribute Inheritance Search , Classes and Instances , Classes Generate Multiple Instance Objects object.attribute expression, Attribute Inheritance Search open call, (Python 2.6), Coding Unicode Strings in Python 2.6 open function, Files , Other File-Like Tools , Files mode string argument, Text and Binary Files operator overloading, Type Categories Revisited , Why Use Classes? , Classes Can Intercept Python Operators –Why Use Operator Overloading? , Step 3: Operator Overloading –Providing Print Displays , Providing Print Displays , Operator Overloading –Object Destruction: __del__ attribute references, Attribute Reference: __getattr__ and __setattr__ –Emulating Privacy for Instance Attributes: Part 1 attribute privacy, Emulating Privacy for Instance Attributes: Part 1 Boolean tests, Boolean Tests: __bool__ and __len__ call expressions, Call Expressions: __call__ –Function Interfaces and Callback-Based Code function interfaces, Function Interfaces and Callback-Based Code common operator overloading methods, Common Operator Overloading Methods comparisons, Comparisons: __lt__, __gt__, and Others constructors and expressions, Constructors and Expressions: __init__ and __sub__ index iteration, Index Iteration: __getitem__ indexing and slicing, Indexing and Slicing: __getitem__ and __setitem__ –Intercepting Slices Python 2.6, Intercepting Slices iterator objects, Iterator Objects: __iter__ and __next__ multiple iterators on one object, Multiple Iterators on One Object user defined iterators, User-Defined Iterators justification, Why Use Operator Overloading? membership, Membership: __contains__, __iter__, and __getitem__ comparisons, Python 2.6, Membership: __contains__, __iter__, and __getitem__ object destruction, Object Destruction: __del__ overloading methods, Increasing Levels of Magic overloading methods in Python 2.6, OOP and Delegation: “Wrapper” Objects overview, The Basics –Common Operator Overloading Methods right-side and in-place addition, Right-Side and In-Place Addition: __radd__ and __iadd__ –In-Place Addition string representation, String Representation: __repr__ and __str__ –String Representation: __repr__ and __str__ operator precedence, Python Expression Operators , Mixed operators follow operator precedence optimization, Development Tools for Larger Projects ORMs (object-relational mappers), Future Directions OverflowError class, Built-in Exception Classes P package imports, Module Packages justification, Why Use Package Imports? –A Tale of Three Systems import versus from, A Tale of Three Systems root directory, A Tale of Three Systems packages and search path settings, Packages and Search Path Settings package relative imports, Package Relative Imports –Imports are still relative to the CWD (again) absolute package paths, versus, Relative imports versus absolute package paths basics, Relative Import Basics examples, Relative Imports in Action –Imports are still relative to the CWD (again) imports outside packages, Imports outside packages imports relative to CWD, Imports are still relative to the CWD imports still relative to CWD, Imports are still relative to the CWD (again) imports within packages, Imports within packages modules, selecting with relative and absolute
imports, Selecting modules with relative and absolute
imports justification, Why Relative Imports? module lookup rules summary, Module Lookup Rules Summary Python 3.0, The relative imports solution in 3.0 changes, Changes in Python 3.0 versus 2.6, Relative Import Basics scope, The Scope of Relative Imports packages, Module Packages parallel traversals, Parallel Traversals: zip and map 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 Parrot project, Future Possibilities? parsing, Indexing and Slicing pass statement, break, continue, pass, and the Loop else , pass PATH environment variable, The Interactive Prompt , Python Environment Variables pattern matching, Pattern Matching pdb debugger, Development Tools for Larger Projects PEP (Python Enhancement Proposal) protocol, How Is Python Supported? Perl, How Does Python Stack Up to Language X? , Test Your Knowledge: Answers Person class, Step 1: Making Instances incremental testing, Testing As You Go subclassing, Coding Subclasses version portability, Using Code Two Ways person.py, Step 1: Making Instances Peters, Tim, To Metaclass or Not to Metaclass pickle module, Storing native Python objects with pickle , Pickles and Shelves , Stream Processors Revisited binary data requirement, The pickle Object Serialization Module string serialization (Python 3.0), The pickle Object Serialization Module pizzashop.py, OOP and Composition: “Has-a” Relationships polymorphism, Sequence Operations , How to Break Your Code’s Flexibility , Preview: Operator overloading and polymorphism , Polymorphism in Python , Polymorphism Revisited , OOP Is About Code Reuse dynamic typing and, Dynamic Typing Is Everywhere example, Polymorphism in Action overloading in Python versus other
languages, Overloading by Call Signatures (or Not) pop method, Type-Specific Operations , List method calls , More Dictionary Methods portability, It’s Portable Portable Python, Where to Get Python pow function, Other Built-in Numeric Tools precedence, Python Expression Operators parentheses and, Parentheses group subexpressions precedence rules, Mixed operators follow operator precedence print function, Python’s Statements print operations, Print Operations –Version-Neutral Printing print and stdout, Version-Neutral Printing print function (Python 3.0), The Python 3.0 print Function print statement (Python 2.6), The Python 2.6 print Statement print stream redirection, Print Stream Redirection version-neutral printing, Version-Neutral Printing print statement (Python 2.6), Python’s Statements private, Minimizing from * Damage: _X and __all__ , Emulating Privacy for Instance Attributes: Part 1 , Example: “Private” and “Public” Attributes procedure, Why Use Functions? profile module, Other Suggestions , Development Tools for Larger Projects profilers, Development Tools for Larger Projects program execution, Program Execution –Development implications development implications, Development implications Python compared to other languages, Performance implications program portability, Why Do People Use Python? program shipping options, Development Tools for Larger Projects program structure, imports, Imports and Attributes program units, Python’s Core Data Types programs, Is Python a “Scripting Language”? , System Command Lines and Files , Introducing Python Object Types icons, opening with, Clicking File Icons launching, How You Run Programs additional launch options, Other Launch Options choosing a launch option, Which Option Should I Use? clicking file icons, Clicking File Icons exec function, Using exec to Run Module Files from the command line, Running Files with Command Lines IDLE user interface, The IDLE User Interface input function, The input Trick module imports and reloads, Module Imports and Reloads , import and reload Usage Notes Unix executable scripts, Unix Executable Scripts (#!) Windows automatic file extensions, Using Command Lines and Files running interactively, The Interactive Prompt –Entering multiline statements experimentation, Experimenting testing, Testing saving in files, System Command Lines and Files structure, Python Program Structure Revisited , Python Program Architecture –Standard Library Modules Windows, saving under, Using Command Lines and Files property built-in function, Class Properties , Inserting Code to Run on Attribute Access computed attributes, Computed Attributes decorators, Coding Properties with Decorators first example, A First Example proxy classes, OOP and Delegation: “Wrapper” Objects pseudoprivate attributes, justification, Why Use Pseudoprivate Attributes? pseudoprivate names, Pseudoprivate Class Attributes PSF (Python Software Foundation), How Is Python Supported? Psyco just-in-time compiler, The Psyco just-in-time compiler , Development Tools for Larger Projects .pth file
extension, Path files .pth path file
directories, The Module Search Path PVM (Python Virtual Machine), The Python Virtual Machine (PVM) .py file extension, The Programmer’s View , A First Script , Module Creation py2exe, Frozen Binaries , Development Tools for Larger Projects .pyc file
extension, Byte code compilation , 2. Compile It (Maybe) PyChecker, PyLint, and PyUnit, Development Tools for Larger Projects PyDev, Other IDEs PyDoc, Getting Help , PyDoc: The help Function –PyDoc: HTML Reports , Development Tools for Larger Projects help function, PyDoc: The help Function HTML reports, PyDoc: HTML Reports PyInstaller, Frozen Binaries , Development Tools for Larger Projects PyPy project, Future Possibilities? Python command-line options, Python Command-Line Options –Python Command-Line Options configuration, Configuring Python DOS variables in autoexec.bat, DOS variables (Windows) environment variables, Python Environment Variables path files, Path files setting configuration options, How to Set Configuration Options Unix/Linux shell variables, Unix/Linux shell variables Windows environment variable GUI, Windows environment variable GUI Windows registry, Windows registry installing, Introducing the Python Interpreter Python 2.0 string module, The Original string Module (Gone in 3.0) Python 2.6, About This Fourth Edition backward compatibility to older versions, About This Fourth Edition binary and Unicode strings, handling of, Unicode and Byte Strings Booleans, Boolean Tests: __bool__ and __len__ iteration method X.next( ), Manual Iteration: iter and next nonlocal statement, alternatives to in, Shared state with globals operator overloading methods, OOP and Delegation: “Wrapper” Objects Python 3.0 print function, emulating, Emulating the Python 3.0 print Function using keyword-only arguments, Using Keyword-Only Arguments raw_input function, The input Trick reload function, Module Imports and Reloads string object types, Strings unicode and str operation sets, Coding Unicode Strings in Python 2.6 “new-style” and “classic” classes, The “New-Style” Class Model Python 3.0, About This Fourth Edition built-in attributes, Other Ways to Combine Classes compared 2.x versions, Specific Language Extensions in 2.6 and 3.0 comparisons and sorts, List method calls dictionary changes, Dictionary Changes in Python 3.0 dictionary comparisons, Python 3.0 Dictionary Comparisons extended sequence unpacking, Assignment Statement Forms , Extended Sequence Unpacking in Python 3.0 in for loops, Python 3.0 extended sequence assignment in for
loops function annotations, Function Annotations in 3.0 incompatibility with older versions, About This Fourth Edition input function, The input Trick new iterables, New Iterables in Python 3.0 –Dictionary View Iterators “new-style”
classes, The “New-Style” Class Model older version tools removed from, Specific Language Removals in 3.0 special character coding, Other Unicode Coding Techniques string object types, Strings string type, changes in, String Changes in 3.0 text and binary files, Text and binary files in Python 3.0 Unicode and binary data support, Unicode and Byte Strings unsupported raise syntax, Python 3.0 Exception Chaining: raise from Python interpreter, Introducing the Python Interpreter installing, Installing the Python Interpreter on Linux, Installation Steps on PDAs, Installation Steps on Unix, Installation Steps on Windows, Installation Steps on Windows Vista, Installation Steps website downloads link, Where to Get Python Python programming language, Preface advantages of, Why Do People Use Python? –Developer Productivity common coding gotchas, Common Coding Gotchas compared to other languages, How Does Python Stack Up to Language X? developer productivity and, Developer Productivity development tools, The Python Toolset documentation (see documentation) execution speed, OK, but What’s the Downside? iteration protocol, Iteration protocol integration manuals and resources, For More Help old and new versions, About This Fourth Edition Perl, compared to, Test Your Knowledge: Answers portability, It’s Portable primary implementations of, Python Implementation Alternatives so-called “optional” features, Metaclasses Versus Class Decorators: Round 3 statically-typed languages, compared to, Polymorphism in Python string model, String Basics –Text and Binary Files support, How Is Python Supported? technical strengths, What Are Python’s Technical Strengths? –It’s Named After Monty Python user base, Who Uses Python Today? uses for, What Can I Do with Python? –Gaming, Images, Serial Ports, XML, Robots, and More PYTHONPATH, Python Environment Variables PYTHONPATH directories, The Module Search Path PYTHONSTARTUP, Python Environment Variables PythonWin, Other IDEs , Where to Get Python PyWin32, Where to Get Python Q quizzes, This Book’s Style and Structure Chapter 1: A Python Q&A
Session, Test Your Knowledge: Quiz Chapter 2: How Python Runs
Programs, Chapter Summary Chapter 3: How You Run
Programs, Chapter Summary Chapter 4: Introducing Python
Object Types, Test Your Knowledge: Quiz Chapter 5: Numeric
Types, Chapter Summary Chapter 6: The Dynamic Typing
Interlude, Test Your Knowledge: Quiz Chapter 7: Strings, Chapter Summary Chapter 8: Lists and
Dictionaries, Chapter Summary Chapter 9: Tuples, Files, and
Everything Else, Chapter Summary Chapter 10: Introducing Python
Statements, Chapter Summary Chapter 11: Assignments,
Expressions, and Prints, Chapter Summary Chapter 12: if Tests and Syntax
Rules, Chapter Summary Chapter 13: while and for
Loops, Chapter Summary Chapter 14: Iterations and
Comprehensions, Part 1, Chapter Summary Chapter 15: The Documentation
Interlude, Chapter Summary Chapter 16: Function
Basics, Chapter Summary Chapter 17: Scopes, Chapter Summary Chapter 18: Arguments, Chapter Summary Chapter 19: Advanced Function
Topics, Chapter Summary Chapter 20: Iterations and
Comprehensions, Part 2, Chapter Summary Chapter 21: Modules, the Big
Picture, Chapter Summary Chapter 22: Module Coding
Basics, Chapter Summary Chapter 23: Module
Packages, Chapter Summary Chapter 24: Advanced Module
Topics, Chapter Summary Chapter 25: OOP: The Big
Picture, Chapter Summary Chapter 26: Class Coding
Basics, Chapter Summary Chapter 27: A More Realistic
Example, Chapter Summary Chapter 28: Class Coding
Details, Chapter Summary Chapter 29: Operator
Overloading, Chapter Summary Chapter 30: Designing with
Classes, Chapter Summary Chapter 31: Advanced Class
Topics, Chapter Summary Chapter 32: Exception
Basics, Chapter Summary Chapter 33: Exception Coding
Details, Chapter Summary Chapter 34: Exception
Objects, Chapter Summary Chapter 35: Designing with
Exceptions, Test Your Knowledge: Quiz Chapter 36: Unicode and Byte
Strings, Chapter Summary Chapter 37: Managed
Attributes, Chapter Summary Chapter 38: Decorators, Chapter Summary Chapter 39:
Metaclasses, Chapter Summary quotes escaping, Single- and Double-Quoted Strings Are the Same strings and, Single- and Double-Quoted Strings Are the Same triple quotes, Triple Quotes Code Multiline Block Strings R raise statement, Raising Exceptions , The raise Statement –Python 3.0 Exception Chaining: raise from from clause Python 3.0 exception chaining, Python 3.0 Exception Chaining: raise from nonerror conditions, signaling with, Functions Can Signal Conditions with raise random module, Numbers , Other Built-in Numeric Tools range versus for loops, Common Coding Gotchas range function, Counter Loops: while and range range iterator, The range Iterator support for multiple iterators, Multiple Versus Single Iterators rapid prototyping, Rapid Prototyping rational number objects, Fraction Type raw string literals, Other Ways to Code Strings raw strings, Raw Strings Suppress Escapes raw_input function (Python 2.x), The input Trick re (regular expression) module, Pattern Matching string handling in Python 3.0, The re Pattern Matching Module read method, Files in Action readline method, Files , Files in Action recursive functions, Recursive Functions –Handling Arbitrary Structures arbitrary structures, handling, Handling Arbitrary Structures coding alternatives, Coding Alternatives direct or indirect, Coding Alternatives loop statements, versus, Loop Statements Versus Recursion summation, Summation with Recursion recursive imports, Recursive from Imports May Not Work reduce, Other Iteration Contexts reduce function, Functional Programming Tools: filter and reduce reference counters, Objects Are Garbage-Collected references, Variables, Objects, and References , Variables, Objects, and References copies of objects, versus, References Versus Copies shared references, Shared References –Shared References and Equality equality, Shared References and Equality in-place changes, Shared References and In-Place Changes relative imports, Module Packages reload function, Module Imports and Reloads , Reloading Modules –reload Example example, reload Example from imports and, reload May Not Impact from Imports interactive testing, reload, from, and Interactive Testing import and from, contrasted with, reload Basics transitive module reloads, Transitive Module Reloads –Transitive Module Reloads usage notes, import and reload Usage Notes version 3.0 requirements, Module Imports and Reloads reloadall.py, Transitive Module Reloads remove method, Type-Specific Operations , List method calls repetition, Sequence Operations replace method, Type-Specific Methods repr function, Numbers str, compared to, Numeric Display Formats return statement, Coding Functions , def Statements , Local Variables reverse method, Type-Specific Operations , List method calls round function, Other Built-in Numeric Tools rstrip method, Storing and parsing Python objects in files S SAX parsing, XML Parsing Tools scientific programming, Numeric and Scientific Programming ScientificPython programming extensions, Numeric and Scientific Programming SciPy programming extensions, Numeric and Scientific Programming , Numeric Extensions scopes, Scopes –The Built-in Scope basics, Python Scope Basics built-in scope, The Built-in Scope defaults with loop variables, versus, Scopes versus defaults with loop variables example, Scope Example global statements, Python Scope Basics module files and, Minimize Cross-File Changes name resolution and the LEGB rule, Name Resolution: The LEGB Rule namespaces, Python Scope Basics nested functions and, Scopes and Nested Functions –Arbitrary scope nesting nonlocal, Python Scope Basics rules, Scope Rules script0.py, The Programmer’s View script1.py, A First Script running with an import, Module Imports and Reloads scripts, Is Python a “Scripting Language”? , System Command Lines and Files search tables (see dictionaries) self argument, Methods semicolon (;), End of line is end of statement send method, Extended generator function protocol: send versus
next sequence assignment statements, Assignment Statement Forms sequence assignments, Sequence Assignments –Advanced sequence assignment patterns sequence operations, Sequence Operations sequences, Strings set comprehensions, 3.0 Comprehension Syntax Summary set numeric type, Sets –Why sets? dictionaries, compared to, Set literals in Python 3.0 immutable constraints and frozen sets, Immutable constraints and frozen sets Python 2.6, Set basics in Python 2.6 Python 3.0, Set literals in Python 3.0 set comprehensions in Python 3.0, Set comprehensions in Python 3.0 set object type, Other Core Types setsubclass.py, Extending Types by Subclassing shared references, Shared References –Shared References and Equality equality, Shared References and Equality in-place changes, Shared References and In-Place Changes Shedskin C++ translator, The Shedskin C++ translator , Development Tools for Larger Projects shelve module, Pickles and Shelves –Updating Objects on a Shelve , Stream Processors Revisited advantages and disadvantages, Exploring Shelves Interactively database client, Exploring Shelves Interactively database files, Exploring Shelves Interactively object storage in shelve databases, Storing Objects on a Shelve Database shelves and dictionaries, Pickles and Shelves updating a shelve’s objects, Updating Objects on a Shelve simple functions, Static Methods in 2.6 and 3.0 single quotes (') and strings, Single- and Double-Quoted Strings Are the Same singleton, Using and Defining Decorators site module, The Module Search Path slice assignment in lists, Index and slice assignments slice objects, Extended slicing: the third limit and slice objects slicing, Sequence Operations , Indexing and Slicing , Indexing and Slicing example, Extended slicing: the third limit and slice objects extended slicing, Extended slicing: the third limit and slice objects loops, usage in, Nonexhaustive Traversals: range and Slices software components, Step 4: Customizing Behavior by Subclassing sort method, Type-Specific Operations , List method calls , Common Coding Gotchas , Full Credit sorted function, Sorting Keys: for Loops , Other Iteration Contexts sorts in Python 3.0, List method calls source code, Byte code compilation source file character set encoding
declarations, Source File Character Set Encoding Declarations spaces, Python Syntax Rules special characters, Character Encoding Schemes split method, Storing and parsing Python objects in files 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 square roots, Other Built-in Numeric Tools stack trace, Default Exception Handler , Example: Default Behavior Stackless Python, Other Execution Options standard library, Why Do People Use Python? , Standard Library Modules library directories, The Module Search Path standard manual set, The Standard Manual Set standard output stream (stdout), Print Operations state information, User-Defined Classes , Coding Constructors state retention, Why nonlocal? –State with function attributes , Function Interfaces and Callback-Based Code , State Information Retention Options –Enclosing scopes and nonlocals state with classes, State with classes (preview) statements, Introducing Python Object Types , Introducing Python Statements –Chapter Summary assignment statements (see assignment statements) compound statements, What Python Adds differences from other C-like languages, What Python Removes end-of-line, End of line is end of statement expression statements, Expression Statements in-place changes, Expression Statements and In-Place Changes indentation syntax, Why Indentation Syntax? multiline statements, Statement Delimiters: Lines and Continuations Python 3.0 statement set, Python’s Statements syntax, A Tale of Two ifs block rule special case, Block rule special case colon (:), What Python Adds indentation, End of indentation is end of block interactive loops, A Quick Example: Interactive Loops –Nesting Code Three Levels Deep semicolons, Statement rule special cases statement separators, Statement rule special cases static methods, Other Method Call Possibilities , Unbound Methods are Functions in 3.0 , Static and Class Methods –Counting Instances with Static Methods alternatives to, Static Method Alternatives coding with decorator syntax, Function Decorator Basics counting instances, Counting Instances with Static Methods Python 2.6 and 3.0, Static Methods in 2.6 and 3.0 using, Using Static and Class Methods staticmethod function, Using Static and Class Methods steps, Extended slicing: the third limit and slice objects StopIteration exception, The Iteration Protocol: File Iterators str, Numbers , Strings , Strings , String Conversion Tools repr, compared to, Numeric Display Formats str object type data encoding in, Text and Binary Files str string type, Python’s String Types Python 2.6 operation set, Coding Unicode Strings in Python 2.6 Python 3.0 compared to 2.x, Python’s String Types Unicode and, Other Ways to Code Strings stream processors, Stream Processors Revisited stream redirection, Running Files with Command Lines strides, Extended slicing: the third limit and slice objects string exceptions, Class-Based Exceptions deprecation of, String Exceptions Are Right Out! string formatting, String Formatting Expressions –Dictionary-Based String Formatting Expressions advanced expressions, Advanced String Formatting Expressions dictionary-based formatting expressions, Dictionary-Based String Formatting Expressions string formatting type codes, Advanced String Formatting Expressions string formatting method calls, String Formatting Method Calls –Possible future deprecation? format method, The Basics –Possible future deprecation? % formatting expression, compared to, Comparison to the % Formatting Expression justification for, Why the New Format Method? keys, attributes, and offsets, Adding Keys, Attributes, and Offsets string methods, String Methods –The Original string Module (Gone in 3.0) additional examples, Other Common String Methods in Action changing strings example, String Method Examples: Changing Strings parsing text example, String Method Examples: Parsing Text Python 2.x string module, The Original string Module (Gone in 3.0) string method calls to format method, Adding Specific Formatting string method calls, Python 3.0, String Methods string object type, Strings –Pattern Matching , Strings –Triple Quotes Code Multiline Block Strings coding special characters, Other Ways to Code Strings pattern matching, Pattern Matching raw string literals, Other Ways to Code Strings sequence operations and, Sequence Operations string literals, String Literals –Triple Quotes Code Multiline Block Strings common literals and operations, Strings escape sequences, Escape Sequences Represent Special Bytes –Escape Sequences Represent Special Bytes raw strings and escapes, Raw Strings Suppress Escapes single and double quoted strings, Single- and Double-Quoted Strings Are the Same string backslash characters, Escape Sequences Represent Special Bytes triple quotes, Triple Quotes Code Multiline Block Strings version 3.0 changes, String Changes in 3.0 versions 2.6 and 3.0 string types, Strings string operations, Strings in Action –Changing Strings basic operations, Basic Operations changing strings, Changing Strings indexing, Indexing and Slicing , Indexing and Slicing slicing, Indexing and Slicing , Indexing and Slicing extended slicing, Extended slicing: the third limit and slice objects string conversions, String Conversion Tools character code conversions, Character code conversions strings, String Basics 16- and 32-bit Unicode values, coding of, Other Unicode Coding Techniques ASCII text, coding, Coding ASCII Text bytearray objects, using, Using 3.0 (and 2.6) bytearray Objects –Using 3.0 (and 2.6) bytearray Objects bytes objects (Python 3.0), Using 3.0 Bytes Objects –Mixing String Types method calls, Method Calls sequence operations, Sequence Operations bytes string type making bytes objects, Other Ways to Make bytes Objects character encoding schemes and, Character Encoding Schemes encoding conversions, Converting Encodings escape sequence coding by type, Other Unicode Coding Techniques examples of usage (Python 3.0), Python 3.0 Strings in Action –Conversions literals and basic properties, Literals and Basic Properties mixing string types, Mixing String Types mutability or immutability of string
types, Literals and Basic Properties non-ASCII text, coding, Coding Non-ASCII Text non-ASCII text, encoding and decoding, Encoding and Decoding Non-ASCII text pickle object serialization module (Python
3.0), The pickle Object Serialization Module Python 3.0 string types, usage, Using 3.0 (and 2.6) bytearray Objects re pattern matching module (Python 3.0), The re Pattern Matching Module source file character set encoding
declarations, Source File Character Set Encoding Declarations string methods, Type-Specific Methods string types, Python’s String Types struct binary data module (Python 3.0), The struct Binary Data Module text and binary files, Using Text and Binary Files BOM in Python 3.0, Handling the BOM in 3.0 file modes in Python 3.0, Text and Binary Modes in 3.0 type and content mismatches, Type and Content Mismatches Unicode in Python 2.6, Unicode Files in 2.6 type conversions, Conversions Unicode files, using, Using Unicode Files reading and writing in Python 3.0, Reading and Writing Unicode in 3.0 unicode strings, coding, Coding Unicode Strings Unicode strings, Python 2.6 coding, Coding Unicode Strings in Python 2.6 XML parsing tools, XML Parsing Tools strong typing, Python’s Core Data Types struct module string handling, Python 3.0, The struct Binary Data Module subclasses, Attribute Inheritance Search , Classes Are Customized by Inheritance , Step 4: Customizing Behavior by Subclassing –OOP: The Big Idea coding, Coding Subclasses –OOP: The Big Idea augmenting methods, Augmenting Methods: The Bad Way –Augmenting Methods: The Good Way inheritance, customization, and extension, Inherit, Customize, and Extend OOP, as illustration of, OOP: The Big Idea polymorphism, Polymorphism in Action sum function, Other Built-in Numeric Tools Super class, Class Interface Techniques superclasses, Attribute Inheritance Search , Classes Are Customized by Inheritance abstract superclasses, Abstract Superclasses –Python 2.6 and 3.0 Abstract Superclasses syntax rules, A Tale of Two ifs –Block rule special case , Python Syntax Rules –A Few Special Cases indentation, Block Delimiters: Indentation Rules multiline statements, Statement Delimiters: Lines and Continuations open syntactic pairs rule, A Few Special Cases sys.exc_info, Running In-Process Tests –More on sys.exc_info sys.exec_info, The Context Management Protocol , Coding Exceptions Classes sys.exit(statuscode) call, Catching Too Much: Avoid Empty except and Exception sys.getdefaultencoding function, String Changes in 3.0 sys.modules table, How Imports Work sys.path list, The Module Search Path , The sys.path List , Changing the Module Search Path system namespace partitioning and modules, Why Use Modules? systems programming, Systems Programming T termination actions, Termination Actions testdriver function, Running In-Process Tests tester, nonlocal in Action testing of code, Testing As You Go testmixin.py, Listing instance attributes with __dict__ testprint30.py, Emulating the Python 3.0 print Function text files, Files , Text and binary files in Python 3.0 , Text and Binary Files , Text File Basics in Python 3.0, Text and Binary Modes in 3.0 text-mode files, Using Text and Binary Files text.py, Source File Character Set Encoding Declarations threading, Basic Usage threenames.py, The Grander Module Story: Attributes time module, Timing Module alternatives, Timing Module Alternatives timeit module, Other Suggestions timer module, keyword-only arguments, Using keyword-only arguments in 3.0 tkinter, IDLE Basics getting support on Linux, Python Environment Variables settings, Python Environment Variables top-level code, Common Coding Gotchas top-level file, Module Imports and Reloads , How to Structure a Program traceback, More on sys.exc_info transitive module reloads, Transitive Module Reloads –Transitive Module Reloads triple quotes, Triple Quotes Code Multiline Block Strings True and False, The Built-in Scope True and False Boolean values, Booleans true and false values, The Meaning of True and False in Python true division, Python Expression Operators , Division: Classic, Floor, and True truth tests, Truth Tests try except statement, Termination Actions try statement, Missing Keys: if Tests , Python’s Statements , Why Use Exceptions? , Example: Default Behavior (see also exceptions) debugging with, Debugging with Outer try Statements except statement and, Catching Exceptions nested try statements, Nesting Exception Handlers –Example: Syntactic Nesting Python 2.5 and later, Exception Coding Details try except/else, The try/except/else Statement –Example: Catching Built-in Exceptions try statement clause forms, try Statement Clauses –try Statement Clauses try/else clause, The try else Clause try/finally statement, The try/finally Statement –Example: Coding Termination Actions with try/finally coding termination actions, Example: Coding Termination Actions with try/finally unified try/except/finally, Unified try/except/finally –Unified try Example example, Unified try Example nesting finally and except, Combining finally and except by Nesting statement syntax, Unified try Statement Syntax try/finally statement, Exception Roles , Termination Actions file and server connection closure, Closing Files and Server Connections tuple object type, Tuples tuple-unpacking assignment statements, Assignment Statement Forms tuples, Variables and Basic Expressions , Tuples, Files, and Everything Else , Tuples –Why Lists and Tuples? common literals and operations, Tuples conversions, methods, and immutability, Conversions, methods, and immutability in for loops, Tuple assignment in for loops immutability and tuple contents, Conversions, methods, and immutability lists, compared to, Why Lists and Tuples? sorting, Conversions, methods, and immutability supported sequence operations, Tuples in Action syntax with parentheses and commas, Tuple syntax peculiarities: Commas and parentheses type class, Metaclasses Are Subclasses of Type type hierarchies, Python’s Type Hierarchies type object type, How to Break Your Code’s Flexibility , Type Objects , Classes Are Instances of type typesubclass.py, Extending Types by Subclassing U unbound methods, Methods Are Objects: Bound or Unbound , Static Methods in 2.6 and 3.0 Python 3.0 status as functions, Unbound Methods are Functions in 3.0 undefined name exception, Abstract Superclasses underscore (_), Minimizing from * Damage: _X and __all__ Unicode, Character Encoding Schemes strings, coding of, Coding Unicode Strings text, handling in versions 2.6 and 3.0, String Changes in 3.0 Unicode files, Using Unicode Files reading and writing (Python 3.0), Reading and Writing Unicode in 3.0 decoding mismatches, Decoding mismatches file input decoding, File input decoding file output encoding, File output encoding manual encoding, Manual encoding unicode string type (Python 2.6), Coding Unicode Strings in Python 2.6 unicode string type (Python 2.x), Python’s String Types , Coding Unicode Strings in Python 2.6 unicode strings, Strings union function, Generalized Set Functions unit tests with __name__ attribute, Unit Tests with __name__ unittest, Development Tools for Larger Projects Unix env lookup trick, Unix Executable Scripts (#!) executable scripts, Unix Executable Scripts (#!) Python command line, starting, The Interactive Prompt Unladen Swallow project, Future Possibilities? update method, More Dictionary Methods user base of Python language, Who Uses Python Today? user-defined classes, User-Defined Classes user-defined exceptions, User-Defined Exceptions UTF-8 encoding, Character Encoding Schemes utility modules, Built-in Numeric Tools V values method, More Dictionary Methods , Dictionary View Iterators van Rossum, Guido, It’s Free variables, Variables and Basic Expressions , Variables, Objects, and References –Variables, Objects, and References declaration, Variables and Basic Expressions initialization, Imports Happen Only Once local variables, Local Variables scope, Python Scope Basics variable name rules, Variable Name Rules –Names have no type, but objects do vars, Dictionary-Based String Formatting Expressions W websites, Future Directions while loop, Sorting Keys: for Loops versus for loops, Common Coding Gotchas while statement, while and for Loops range function and, Counter Loops: while and range Windows automatic file extensions, Using Command Lines and Files executable files, displaying output, The input Trick icon clicks for program initiation, Clicking Icons on Windows IDLE user interface and, IDLE Basics program files, opening with icons, Clicking File Icons Python command line, starting in, The Interactive Prompt Python files, running in, Running Files with Command Lines Python standard manual set, The Standard Manual Set Windows Notepad, file encoding specification, Handling the BOM in 3.0 with statement, Decimal context manager , Other File Tools , The try/finally Statement with/as extension, Python’s Statements with/as statement, Termination Actions , with/as Context Managers –The Context Management Protocol context management protocol, The Context Management Protocol usage, Basic Usage wrapper classes, OOP and Delegation: “Wrapper” Objects wrapper objects, Managing Calls and Instances wrappers, catching exceptions with, What Should Be Wrapped write method, Files in Action
..................Content has been hidden....................
You can't read the all page of ebook, please click
here login for view all page.