Learning Python, 6th Edition

Book description

Get a comprehensive, in-depth introduction to the core Python language with this hands-on book. Based on author Mark Lutz's popular training course, this updated sixth edition will help you quickly write efficient, high-quality code with Python. It's an ideal way to begin, whether you're new to programming or a professional developer versed in other languages.

Complete with quizzes, exercises, and helpful illustrations, this easy-to-follow self-paced tutorial gets you started with Python 3.12 and all other releases in use today. With a pragmatic focus on what you need to know, it also introduces some advanced language features that have become increasingly common in Python code.

This book helps you:

  • Explore Python's built-in object types such as strings, lists, dictionaries, and files
  • Create and process objects with Python statements, and learn Python's syntax model
  • Use functions and functional programming to avoid redundancy and maximize reuse
  • Organize code into larger components with modules and packages
  • Code robust programs with Python's exception handling and development tools
  • Apply object-oriented programming and classes to make code customizable
  • Survey advanced Python tools including decorators, descriptors, and metaclasses
  • Write idiomatic Python code that runs portably across a wide variety of platforms

Publisher resources

View/Submit Errata

Table of contents

  1. Preface
    1. Python
    2. This Book
    3. This Edition
    4. Media Choices
    5. Updates and Examples
    6. Conventions and Reuse
    7. Acknowledgments
  2. I. Getting Started
  3. 1. A Python Q&A Session
    1. Why Do People Use Python?
      1. Software Quality
      2. Developer Productivity
    2. Is Python a “Scripting Language”?
    3. OK, but What’s the Downside?
    4. Who Uses Python Today?
    5. What Can I Do with Python?
      1. Systems Programming
      2. GUIs and UIs
      3. Internet and Web Scripting
      4. Component Integration
      5. Database Access
      6. Rapid Prototyping
      7. Numeric and Scientific Programming
      8. And More: AI, Games, Images, QA, Excel, Apps…
    6. What Are Python’s Technical Strengths?
      1. It’s Object-Oriented and Functional
      2. It’s Free and Open
      3. It’s Portable
      4. It’s Powerful
      5. It’s Mixable
      6. It’s Relatively Easy to Use
      7. It’s Relatively Easy to Learn
    7. Chapter Summary
    8. Test Your Knowledge: Quiz
    9. Test Your Knowledge: Answers
  4. 2. How Python Runs Programs
    1. Introducing the Python Interpreter
    2. Program Execution
      1. The Programmer’s View
      2. Python’s View
    3. Execution-Model Variations
      1. Python Implementation Alternatives
      2. Standalone Executables
      3. Future Possibilities
    4. Chapter Summary
    5. Test Your Knowledge: Quiz
    6. Test Your Knowledge: Answers
  5. 3. How You Run Programs
    1. Installing Python
    2. Interactive Code
      1. Starting an Interactive REPL
      2. Where to Run: Code Folders
      3. What Not to Type: Prompts and Comments
      4. Other Python REPLs
      5. Running Code Interactively
      6. Why the Interactive Prompt?
    3. Program Files
      1. A First Script
      2. Running Files with Command Lines
      3. Command-Line Usage Variations
    4. Other Ways to Run Files
      1. Clicking and Tapping File Icons
      2. The IDLE Graphical User Interface
      3. Other IDEs for Python
      4. Smartphone Apps
      5. WebAssembly for Browsers
      6. Jupyter Notebooks for Science
      7. Ahead-of-Time Compilers for Speed
      8. Running Code in Code
      9. Other Launch Options
    5. Which Option Should I Use?
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
    8. Test Your Knowledge: Answers
    9. Test Your Knowledge: Part I Exercises
  6. II. Objects and Operations
  7. 4. Introducing Python Objects
    1. The Python Conceptual Hierarchy
    2. Why Use Built-in Objects?
    3. Python’s Core Object Types
    4. Numbers
    5. Strings
      1. Sequence Operations
      2. Immutability
      3. Type-Specific Methods
      4. Getting Help
      5. Other Ways to Code Strings
      6. Unicode Strings
    6. Lists
      1. Sequence Operations
      2. Type-Specific Operations
      3. Bounds Checking
      4. Nesting
      5. Comprehensions
    7. Dictionaries
      1. Mapping Operations
      2. Nesting Revisited
      3. Missing Keys: if Tests
      4. Item Iteration: for Loops
    8. Tuples
      1. Why Tuples?
    9. Files
      1. Unicode and Byte Files
      2. Other File-Like Tools
    10. Other Object Types
      1. Sets
      2. Booleans and None
      3. Types
      4. Type Hinting
      5. User-Defined Objects
      6. And Everything Else
    11. Chapter Summary
    12. Test Your Knowledge: Quiz
    13. Test Your Knowledge: Answers
  8. 5. Numbers and Expressions
    1. Numeric Object Basics
      1. Numeric Literals
      2. Built-in Numeric Tools
    2. Python Expression Operators
      1. Mixed Operators: Precedence
      2. Parentheses Group Subexpressions
      3. Mixed Types Are Converted Up
      4. Preview: Operator Overloading and Polymorphism
    3. Numbers in Action
      1. Variables and Basic Expressions
      2. Numeric Display Formats
      3. Comparisons Operators
      4. Division Operators
      5. Integer Precision
      6. Complex Numbers
      7. Hex, Octal, and Binary
      8. Bitwise Operations
      9. Underscore Separators in Numbers
      10. Other Built-in Numeric Tools
    4. Other Numeric Objects
      1. Decimal Objects
      2. Fraction Objects
      3. Set Objects
      4. Boolean Objects
    5. Numeric Extensions
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
    8. Test Your Knowledge: Answers
  9. 6. The Dynamic Typing Interlude
    1. The Case of the Missing Declaration Statements
      1. Variables, Objects, and References
      2. Types Live with Objects, Not Variables
      3. Objects Are Garbage-Collected
    2. Shared References
      1. Shared References and In-Place Changes
      2. Shared References and Equality
    3. Dynamic Typing Is Everywhere
    4. Type Hinting: Optional, Unused, and Why?
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
  10. 7. String Fundamentals
    1. String Object Basics
    2. String Literals
      1. Single and Double Quotes Are the Same
      2. Escape Sequences Are Special Characters
      3. Raw Strings Suppress Escapes
      4. Triple Quotes and Multiline Strings
    3. Strings in Action
      1. Basic Operations
      2. Indexing and Slicing
      3. String Conversion Tools
      4. “Changing” Strings Part 1: Sequence Operations
    4. String Methods
      1. Method Call Syntax
      2. All String Methods (Today)
      3. “Changing” Strings, Part 2: String Methods
      4. More String Methods: Parsing Text
      5. Other Common String Methods
    5. String Formatting: The Triathlon
      1. String-Formatting Options
      2. The String-Formatting Expression
      3. The String-Formatting Method
      4. The F-String Formatting Literal
      5. And the Winner Is…
    6. General Type Categories
      1. Types Share Operation Sets by Categories
      2. Mutable Types Can Be Changed in Place
    7. Chapter Summary
    8. Test Your Knowledge: Quiz
    9. Test Your Knowledge: Answers
  11. 8. Lists and Dictionaries
    1. Lists
    2. Lists in Action
      1. Basic List Operations
      2. Indexing and Slicing
      3. Changing Lists in Place
      4. More List Methods
      5. Iteration, Comprehensions, and Unpacking
      6. Other List Operations
    3. Dictionaries
    4. Dictionaries in Action
      1. Basic Dictionary Operations
      2. Changing Dictionaries in Place
      3. More Dictionary Methods
      4. Other Dictionary Makers
      5. Dictionary Comprehensions
      6. Key Insertion Ordering
      7. Dictionary “Union” Operator
      8. Intermission: Books Database
      9. Dictionary Usage Tips
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
  12. 9. Tuples, Files, and Everything Else
    1. Tuples
      1. Tuples in Action
      2. Why Lists and Tuples?
      3. Records Revisited: Named Tuples
    2. Files
      1. Opening Files
      2. Using Files
      3. Files in Action
      4. Text and Binary Files: The Short Story
      5. Storing Objects with Conversions
      6. Storing Objects with pickle
      7. Storing Objects with JSON
      8. Storing Objects with Other Tools
      9. File Context Managers
      10. Other File Tools
    3. Core Types Review and Summary
      1. Object Flexibility
      2. References Versus Copies
      3. Comparisons, Equality, and Truth
      4. The Meaning of True and False in Python
      5. Python’s Type Hierarchies
      6. Type Objects
    4. Other Types in Python
    5. Built-in Type Gotchas
      1. Assignment Creates References, Not Copies
      2. Repetition Adds One Level Deep
      3. Beware of Cyclic Data Structures
      4. Immutable Types Can’t Be Changed in Place
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
    8. Test Your Knowledge: Answers
    9. Test Your Knowledge: Part II Exercises
  13. III. Statements and Syntax
  14. 10. Introducing Python Statements
    1. The Python Conceptual Hierarchy Revisited
    2. Python’s Statements
    3. A Tale of Two ifs
      1. What Python Adds
      2. What Python Removes
      3. Why Indentation Syntax?
      4. A Few Special Cases
    4. A Quick Example: Interactive Loops
      1. A Simple Interactive Loop
      2. Doing Math on User Inputs
      3. Handling Errors by Testing Inputs
      4. Handling Errors with try Statements
      5. Supporting Floating-Point Numbers
      6. Nesting Code Three Levels Deep
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
  15. 11. Assignments, Expressions, and Prints
    1. Assignments
      1. Assignment Syntax Forms
      2. Basic Assignments
      3. Sequence Assignments
      4. Extended Unpacking Assignments
      5. Multiple-Target Assignments
      6. Augmented Assignments
      7. Named Assignment Expressions
      8. Variable Name Rules
    2. Expression Statements
      1. Expression Statements and In-Place Changes
    3. Print Operations
      1. The print Function
      2. Print Stream Redirection
    4. Chapter Summary
    5. Test Your Knowledge: Quiz
    6. Test Your Knowledge: Answers
  16. 12. if and match Selections
    1. if Statements
      1. General Format
      2. Basic Examples
      3. Multiple-Choice Selections
    2. Match Statements
      1. Basic match Usage
      2. Advanced match Usage
    3. Python Syntax Revisited
      1. Block Delimiters: Indentation Rules
      2. Statement Delimiters: Lines and Continuations
      3. Special Syntax Cases in Action
    4. Truth Values Revisited
    5. The if/else Ternary Expression
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
    8. Test Your Knowledge: Answers
  17. 13. while and for Loops
    1. while Loops
      1. General Format
      2. Examples
    2. break, continue, pass, and the Loop else
      1. General Loop Format
      2. pass
      3. continue
      4. break
      5. Loop else
    3. for Loops
      1. General Format
      2. Examples
    4. Loop Coding Techniques
      1. Counter Loops: range
      2. Sequence Scans: while, range, and for
      3. Sequence Shufflers: range and len
      4. Skipping Items: range and Slices
      5. Changing Lists: range and Comprehensions
      6. Parallel Traversals: zip
      7. Offsets and Items: enumerate
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
  18. 14. Iterations and Comprehensions
    1. Iterations
      1. The Iteration Protocol
      2. Other Built-in Iterables
    2. Comprehensions
      1. List Comprehension Basics
      2. List Comprehensions and Files
      3. Extended List Comprehension Syntax
      4. Comprehensions Cliff-Hanger
    3. Iteration Tools
    4. Other Iteration Topics
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
  19. 15. The Documentation Interlude
    1. Python Documentation Sources
      1. # Comments
      2. The dir Function
      3. Docstrings and __doc__
      4. Pydoc: The help Function
      5. Pydoc: HTML Reports
      6. Beyond Docstrings: Sphinx
      7. The Standard Manuals
      8. Web Resources
    2. Common Coding Gotchas
    3. Chapter Summary
    4. Test Your Knowledge: Quiz
    5. Test Your Knowledge: Answers
    6. Test Your Knowledge: Part III Exercises
  20. IV. Functions and Generators
  21. 16. Function Basics
    1. Why Use Functions?
    2. Function Coding Overview
      1. Basic Function Tools
      2. Advanced Function Tools
      3. General Function Concepts
      4. def Statements
      5. return Statements
      6. def Executes at Runtime
      7. lambda Makes Anonymous Functions
    3. A First Example: Definitions and Calls
      1. Definition
      2. Calls
      3. Polymorphism in Python
    4. A Second Example: Intersecting Sequences
      1. Definition
      2. Calls
      3. Polymorphism Revisited
      4. Segue: Local Variables
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
  22. 17. Scopes
    1. Python Scopes Basics
      1. Scopes Overview
      2. Name Resolution: The LEGB Rule
      3. Scopes Examples
      4. The Built-in Scope
    2. The global Statement
      1. Program Design: Minimize Global Variables
      2. Program Design: Minimize Cross-File Changes
      3. Other Ways to Access Globals
    3. Nested Functions and Scopes
      1. Nested Scopes Overview
      2. Nested Scopes Examples
      3. Closures and Factory Functions
      4. Arbitrary Scope Nesting
    4. The nonlocal Statement
      1. nonlocal Basics
      2. nonlocal in Action
      3. nonlocal Boundary Cases
    5. State-Retention Options
      1. Nonlocals: Changeable, Per-Call, LEGB
      2. Globals: Changeable but Shared
      3. Function Attributes: Changeable, Per-Call, Explicit
      4. Classes: Changeable, Per-Call, OOP
      5. And the Winner Is…
    6. Scopes and Argument Defaults
      1. Loops Require Defaults, not Scopes
    7. Chapter Summary
    8. Test Your Knowledge: Quiz
    9. Test Your Knowledge: Answers
  23. 18. Arguments
    1. Argument-Passing Basics
      1. Arguments and Shared References
      2. Avoiding Mutable Argument Changes
      3. Simulating Output Parameters and Multiple Results
    2. Special Argument-Matching Modes
      1. Argument Matching Overview
      2. Argument Matching Syntax
      3. Argument Passing Details
      4. Keyword and Default Examples
      5. Arbitrary Arguments Examples
      6. Keyword-Only Arguments
      7. Positional-Only Arguments
    3. Argument Ordering: The Gritty Details
      1. Definition Ordering
      2. Calls Ordering
    4. Example: The min Wakeup Call
      1. Full Credit
      2. Bonus Points
      3. The Punch Line
    5. Example: Generalized Set Functions
      1. Testing the Code
    6. Example: Rolling Your Own Print
      1. Using Keyword-Only Arguments
    7. Chapter Summary
    8. Test Your Knowledge: Quiz
    9. Test Your Knowledge: Answers
  24. 19. Function Odds and Ends
    1. Function Design Concepts
    2. Recursive Functions
      1. Summation with Recursion
      2. Coding Alternatives
      3. Loop Statements Versus Recursion
      4. Handling Arbitrary Structures
    3. Function Tools: Attributes, Annotations, Etc.
      1. The First-Class Object Model
      2. Function Introspection
      3. Function Attributes
      4. Function Annotations and Decorations
    4. Anonymous Functions: lambda
      1. lambda Basics
      2. Why Use lambda?
      3. How (Not) to Obfuscate Your Python Code
      4. Scopes: lambdas Can Be Nested Too
    5. Functional Programming Tools
      1. Mapping Functions over Iterables: map
      2. Selecting Items in Iterables: filter
      3. Combining Items in Iterables: reduce
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
    8. Test Your Knowledge: Answers
  25. 20. Comprehensions and Generations
    1. Comprehensions: The Final Act
      1. List Comprehensions Review
      2. Formal Comprehension Syntax
      3. Example: List Comprehensions and Matrixes
    2. Generator Functions and Expressions
      1. Generator Functions: yield Versus return
      2. Generator Expressions: Iterables Meet Comprehensions
      3. Generator Functions Versus Generator Expressions
      4. Generator Odds and Ends
    3. Example: Shuffling Sequences
      1. Scrambling Sequences
      2. Permutating Sequences
    4. Example: Emulating zip and map
      1. Coding Your Own map
      2. Coding Your Own zip and 2.X map
    5. Asynchronous Functions: The Short Story
      1. Async Basics
      2. The Async Wrap-Up
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
    8. Test Your Knowledge: Answers
  26. 21. The Benchmarking Interlude
    1. Benchmarking with Homegrown Tools
      1. Timing Module: Take 1
      2. Timer Module: Take 2
      3. Timing Runner and Script
      4. Iteration Results
      5. More Module Mods
    2. Benchmarking with Python’s timeit
      1. Basic timeit Usage
      2. Automating timeit Benchmarking
    3. Function Gotchas
      1. Local Names Are Detected Statically
      2. Defaults and Mutable Objects
      3. Functions Without returns
      4. Miscellaneous Function Gotchas
    4. Chapter Summary
    5. Test Your Knowledge: Quiz
    6. Test Your Knowledge: Answers
    7. Test Your Knowledge: Part IV Exercises
  27. V. Modules and Packages
  28. 22. Modules: The Big Picture
    1. Module Essentials
    2. Why Use Modules?
    3. Python Program Architecture
      1. How to Structure a Program
      2. Imports and Attributes
      3. Standard Library Modules
    4. How Imports Work
      1. Step 1: Find It
      2. Step 2: Compile It (Maybe)
      3. Step 3: Run It
    5. The Module Search Path
      1. Search-Path Components
      2. Configuring the Search Path
      3. The sys.path List
      4. Module File Selection
      5. Path Outliers: Standalones and Packages
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
    8. Test Your Knowledge: Answers
  29. 23. Module Coding Basics
    1. Creation Modules
      1. Module Filenames
      2. Other Kinds of Modules
    2. Using Modules
      1. The import Statement
      2. The from Statement
      3. The from * Statement
      4. Imports Happen Only Once
      5. Imports are Runtime Assignments
      6. import and from Equivalence
      7. Potential Pitfalls of the from Statement
    3. Module Namespaces
      1. How Files Generate Namespaces
      2. Namespace Dictionaries: __dict__
      3. Attribute Name Qualification
      4. Imports Versus Scopes
      5. Namespace Nesting
    4. Reloading Modules
      1. reload Basics
      2. reload Example
      3. reload Odds and Ends
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
  30. 24. Module Packages
    1. Using Packages
      1. Package Imports
      2. Packages and the Module Search Path
    2. Creating Packages
      1. Basic Package Structure
      2. Package __init__.py Files
      3. Package __main__.py Files
    3. Why Packages?
      1. A Tale of Two Systems
    4. The Roles of __init__.py Files
    5. Package-Relative Imports
      1. Relative and Absolute Imports
      2. Relative-Import Rationales and Trade-Offs
      3. Package-Relative Imports in Action
    6. Namespace Packages
      1. Python Import Models
      2. Namespace-Package Rationales
      3. The Module Search Algorithm
      4. Namespace Packages in Action
    7. Chapter Summary
    8. Test Your Knowledge: Quiz
    9. Test Your Knowledge: Answers
  31. 25. Module Odds and Ends
    1. Module Design Concepts
    2. Data Hiding in Modules
      1. Minimizing from * Damage: _X and __all__
      2. Managing Attribute Access: __getattr__ and __dir__
    3. Enabling Language Changes: __future__
    4. Dual-Usage Modes: __name__ and __main__
      1. Example: Unit Tests with __name__
    5. The as Extension for import and from
    6. Module Introspection
      1. Example: Listing Modules with __dict__
    7. Importing Modules by Name String
      1. Running Code Strings
      2. Direct Calls: Two Options
      3. Example: Transitive Module Reloads
    8. Module Gotchas
      1. Module Name Clashes: Package and Package-Relative Imports
      2. Statement Order Matters in Top-Level Code
      3. from Copies Names but Doesn’t Link
      4. from * Can Obscure the Meaning of Variables
      5. reload May Not Impact from Imports
      6. reload, from, and Interactive Testing
      7. Recursive from Imports May Not Work
    9. Chapter Summary
    10. Test Your Knowledge: Quiz
    11. Test Your Knowledge: Answers
    12. Test Your Knowledge: Part V Exercises
  32. VI. Classes and OOP
  33. 26. OOP: The Big Picture
    1. Why Use Classes?
    2. OOP from 30,000 Feet
      1. Attribute Inheritance Search
      2. Classes and Instances
      3. Method Calls
      4. Coding Class Trees
      5. Operator Overloading
      6. OOP Is About Code Reuse
    3. Chapter Summary
    4. Test Your Knowledge: Quiz
    5. Test Your Knowledge: Answers
  34. 27. Class Coding Basics
    1. Classes Generate Multiple Instance Objects
      1. Class Objects Provide Default Behavior
      2. Instance Objects Are Concrete Items
      3. A First Example
    2. Classes Are Customized by Inheritance
      1. A Second Example
      2. Classes Are Attributes in Modules
    3. Classes Can Intercept Python Operators
      1. A Third Example
    4. The World’s Simplest Python Class
      1. Classes: Under the Hood
      2. Records Revisited: Classes Versus Dictionaries
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
  35. 28. A More Realistic Example
    1. Step 1: Making Instances
      1. Coding Constructors
      2. Testing As You Go
      3. Using Code Two Ways
    2. Step 2: Adding Behavior Methods
      1. Coding Methods
    3. Step 3: Operator Overloading
      1. Providing Print Displays
    4. Step 4: Customizing Behavior by Subclassing
      1. Coding Subclasses
      2. Augmenting Methods: The Bad Way
      3. Augmenting Methods: The Good Way
      4. Polymorphism in Action
      5. Inherit, Customize, and Extend
      6. OOP: The Big Idea
    5. Step 5: Customizing Constructors, Too
      1. OOP Is Simpler Than You May Think
      2. Other Ways to Combine Classes: Composites
    6. Step 6: Using Introspection Tools
      1. Special Class Attributes
      2. A Generic Display Tool
      3. Instance Versus Class Attributes
      4. Name Considerations in Tool Classes
      5. Our Classes’ Final Form
    7. Step 7 (Final): Storing Objects in a Database
      1. Pickles and Shelves
      2. Storing Objects on a shelve Database
      3. Exploring Shelves Interactively
      4. Updating Objects on a Shelf
    8. Future Directions
    9. Chapter Summary
    10. Test Your Knowledge: Quiz
    11. Test Your Knowledge: Answers
  36. 29. Class Coding Details
    1. The class Statement
      1. General Syntax and Usage
      2. Example: Class Attributes
    2. Methods
      1. Method Example
      2. Other Method-Call Possibilities
    3. Inheritance
      1. Attribute Tree Construction
      2. Inheritance Fine Print
      3. Specializing Inherited Methods
      4. Class Interface Techniques
      5. Abstract Superclasses
    4. Namespaces: The Conclusion
      1. Simple Names: Global Unless Assigned
      2. Attribute Names: Object Namespaces
      3. The “Zen” of Namespaces: Assignments Classify Names
      4. Nested Classes: The LEGB Scopes Rule Revisited
      5. Namespace Dictionaries: Review
      6. Namespace Links: A Tree Climber
    5. Documentation Strings Revisited
    6. Classes Versus Modules
    7. Chapter Summary
    8. Test Your Knowledge: Quiz
    9. Test Your Knowledge: Answers
  37. 30. Operator Overloading
    1. The Basics
      1. Constructors and Expressions: __init__ and __sub__
      2. Common Operator-Overloading Methods
    2. Indexing and Slicing: __getitem__ and __setitem__
      1. Intercepting Slices
      2. Intercepting Item Assignments
      3. But __index__ Means As-Integer
    3. Index Iteration: __getitem__
    4. Iterable Objects: __iter__ and __next__
      1. User-Defined Iterables
      2. Multiple Iterators on One Object
      3. Coding Alternative: __iter__ plus yield
    5. Membership: __contains__, __iter__, and __getitem__
    6. Attribute Access: __getattr__ and __setattr__
      1. Attribute Reference
      2. Attribute Assignment and Deletion
      3. Other Attribute-Management Tools
      4. Emulating Privacy for Instance Attributes: Part 1
    7. String Representation: __repr__ and __str__
      1. Why Two Display Methods?
      2. Display Usage Notes
    8. Right-Side and In-Place Ops: __radd__ and __iadd__
      1. Right-Side Addition
      2. In-Place Addition
    9. Call Expressions: __call__
      1. Function Interfaces and Callback-Based Code
    10. Comparisons: __lt__, __gt__, and Others
    11. Boolean Tests: __bool__ and __len__
    12. Object Destruction: __del__
      1. Destructor Usage Notes
    13. Chapter Summary
    14. Test Your Knowledge: Quiz
    15. Test Your Knowledge: Answers
  38. 31. Designing with Classes
    1. Python and OOP
      1. Polymorphism Means Interfaces, Not Call Signatures
    2. OOP and Inheritance: “Is-a” Relationships
    3. OOP and Composition: “Has-a” Relationships
      1. Stream Processors Revisited
    4. OOP and Delegation: “Like-a” Relationships
    5. Pseudoprivate Class Attributes
      1. Name Mangling Overview
      2. Why Use Pseudoprivate Attributes?
    6. Method Objects: Bound or Not
      1. Bound Methods in Action
    7. Classes Are Objects: Generic Object Factories
      1. Why Factories?
    8. Multiple Inheritance and the MRO
      1. How Multiple Inheritance Works
      2. How the MRO Works
      3. Attribute Conflict Resolution
      4. Example: A “Mix-in” Attribute Lister
      5. Example: Mapping Attributes to Inheritance Sources
    9. Other Design-Related Topics
    10. Chapter Summary
    11. Test Your Knowledge: Quiz
    12. Test Your Knowledge: Answers
  39. 32. Class Odds and Ends
    1. Extending Built-in Object Types
      1. Extending Types by Embedding
      2. Extending Types by Subclassing
    2. The Python Object Model
      1. Classes are Types are Classes
      2. Some Instances Are More Equal than Others
      3. The Inheritance Bifurcation
      4. The Metaclass/Class Dichotomy
      5. And One “object” to Rule Them All
    3. Advanced Attribute Tools
      1. Slots: Attribute Declarations
      2. Properties: Attribute Accessors
      3. __getattribute__ and Descriptors: Attribute Tools
    4. Static and Class Methods
      1. Why the Special Methods?
      2. Plain-Function Methods
      3. Static Method Alternatives
      4. Using Static and Class Methods
      5. Counting Instances with Static Methods
      6. Counting Instances with Class Methods
    5. Decorators and Metaclasses
      1. Function Decorator Basics
      2. A First Look at User-Defined Function Decorators
      3. A First Look at Class Decorators and Metaclasses
      4. For More Details
    6. The super Function
      1. The super Basics
      2. The super Details
      3. The super Wrap-Up
    7. Class Gotchas
      1. Changing Class Attributes Can Have Side Effects
      2. Changing Mutable Class Attributes Can Have Side Effects, Too
      3. Multiple Inheritance: Order Matters
      4. Scopes in Methods and Classes
      5. Miscellaneous Class Gotchas
      6. “Overwrapping-itis”
    8. Chapter Summary
    9. Test Your Knowledge: Quiz
    10. Test Your Knowledge: Answers
    11. Test Your Knowledge: Part VI Exercises
  40. VII. Exceptions
  41. 33. Exception Basics
    1. Why Use Exceptions?
      1. Exception Roles
    2. Exceptions: The Short Story
      1. Default Exception Handler
      2. Catching Exceptions
      3. Raising Exceptions
      4. User-Defined Exceptions
      5. Termination Actions
    3. Chapter Summary
    4. Test Your Knowledge: Quiz
    5. Test Your Knowledge: Answers
  42. 34. Exception Coding Details
    1. The try Statement
      1. try Statement Clauses
      2. The except and else Clauses
      3. The finally Clause
      4. Combined try Clauses
    2. The raise Statement
      1. Raising Exceptions
      2. The except as hook
      3. Scopes and except as
      4. Propagating Exceptions with raise
      5. Exception Chaining: raise from
    3. The assert Statement
      1. Example: Trapping Constraints (but Not Errors!)
    4. The with statement and Context Managers
      1. Basic with Usage
      2. The Context-Management Protocol
      3. Multiple Context Managers
      4. The Termination-Handlers Shoot-Out
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
  43. 35. Exception Objects
    1. Exception Classes
      1. Coding Exceptions Classes
      2. Why Exception Hierarchies?
    2. Built-in Exception Classes
      1. Built-in Exception Categories
      2. Default Printing and State
    3. Custom Print Displays
    4. Custom State and Behavior
      1. Providing Exception Details
      2. Providing Exception Methods
    5. Exception Groups: Yet Another Star!
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
    8. Test Your Knowledge: Answers
  44. 36. Exception Odds and Ends
    1. Nesting Exception Handlers
      1. Example: Control-Flow Nesting
      2. Example: Syntactic Nesting
    2. Exception Idioms
      1. Breaking Out of Multiple Nested Loops: “go to”
      2. Exceptions Aren’t Always Errors
      3. Functions Can Signal Conditions with raise
      4. Closing Files and Server Connections
      5. Debugging with Outer try Statements
      6. Running In-Process Tests
      7. More on sys.exc_info
      8. Displaying Errors and Tracebacks
    3. Exception Design Tips and Gotchas
      1. What Should Be Wrapped
      2. Catching Too Much: Avoid Empty except and Exception
      3. Catching Too Little: Use Class-Based Categories
    4. Core Language Wrap-Up
      1. The Python Toolset
      2. Development Tools for Larger Projects
    5. Chapter Summary
    6. Test Your Knowledge: Quiz
    7. Test Your Knowledge: Answers
    8. Test Your Knowledge: Part VII Exercises
  45. VIII. Advanced Topics
  46. 37. Unicode and Byte Strings
    1. Unicode Foundations
      1. Character Representations
      2. Character Encodings
    2. Introducing Python String Tools
      1. The str Object
      2. The bytes Object
      3. The bytearray Object
      4. Text and Binary Files
    3. Using Text Strings
      1. Literals and Basic Properties
      2. String Type Conversions
      3. Coding Unicode Strings in Python
      4. Source-File Encoding Declarations
    4. Using Byte Strings
      1. Methods
      2. Sequence Operations
      3. Formatting
      4. Other Ways to Make Bytes
      5. Mixing String Types
      6. The bytearray Object
    5. Using Text and Binary Files
      1. Text-File Basics
      2. Text and Binary Modes
      3. Unicode-Text Files
    6. Unicode, Bytes, and Other String Tools
      1. The re Pattern-Matching Module
      2. The struct Binary-Data Module
      3. The pickle and json Serialization Modules
      4. Filenames in open and Other Filename Tools
    7. The Unicode Twilight Zone
      1. Dropping the BOM in Python
      2. Unicode Normalization: Whither Standard?
    8. Chapter Summary
    9. Test Your Knowledge: Quiz
    10. Test Your Knowledge: Answers
  47. 38. Managed Attributes
    1. Why Manage Attributes?
      1. Inserting Code to Run on Attribute Access
    2. Properties
      1. The Basics
      2. A First Example
      3. Computed Attributes
      4. Coding Properties with Decorators
    3. Descriptors
      1. The Basics
      2. A First Example
      3. Computed Attributes
      4. Using State Information in Descriptors
      5. How Properties and Descriptors Relate
    4. __getattr__ and __getattribute__
      1. The Basics
      2. A First Example
      3. Computed Attributes
      4. __getattr__ and __getattribute__ Compared
      5. Management Techniques Compared
      6. Intercepting Built-in Operation Attributes
    5. Example: Attribute Validations
      1. Using Properties to Validate
      2. Using Descriptors to Validate
      3. Using __getattr__ to Validate
      4. Using __getattribute__ to Validate
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
      1. Test Your Knowledge: Answers
  48. 39. Decorators
    1. What’s a Decorator?
      1. Managing Calls and Instances
      2. Managing Functions and Classes
      3. Using and Defining Decorators
      4. Why Decorators?
    2. The Basics
      1. Function Decorator Basics
      2. Class Decorator Basics
      3. Decorator Nesting
      4. Decorator Arguments
      5. Decorators Manage Functions and Classes, Too
    3. Coding Function Decorators
      1. Tracing Function Calls
      2. Decorator State Retention Options
      3. Class Pitfall: Decorating Methods
      4. Timing Function Calls
      5. Adding Decorator Arguments
    4. Coding Class Decorators
      1. Singleton Classes
      2. Tracing Object Interfaces
      3. Class Pitfall: Retaining Multiple Instances
    5. Example: “Private” and “Public” Attributes
      1. Implementing Private Attributes
      2. Implementation Details I
      3. Generalizing for Public Declarations
      4. Implementation Details II
      5. Delegating Built-In Operations
    6. Example: Validating Function Arguments
      1. The Goal
      2. A Basic Range-Testing Decorator for Positional Arguments
      3. Generalizing for Keywords and Defaults
      4. Implementation Details
      5. Open Issues
      6. Decorator Arguments Versus Function Annotations
    7. Chapter Summary
    8. Test Your Knowledge: Quiz
    9. Test Your Knowledge: Answers
  49. 40. Metaclasses and Inheritance
    1. To Metaclass or Not to Metaclass
      1. The Downside of “Helper” Functions
      2. Metaclasses Versus Class Decorators: Round 1
    2. The Metaclass Model
      1. Classes Are Instances of type
      2. Metaclasses Are Subclasses of Type
      3. Class Statements Call a Type
      4. Class Statements Can Choose a Type
      5. Metaclass Method Protocol
    3. Coding Metaclasses
      1. A Basic Metaclass
      2. Customizing Construction and Initialization
      3. Other Metaclass Coding Techniques
      4. Managing Classes with Metaclasses and Decorators
    4. Inheritance: The Finale
      1. Metaclass Versus Superclass
      2. Metaclass Inheritance
      3. Python Inheritance Algorithm: The Simple Version
      4. Python Inheritance Algorithm: The Less Simple Version
      5. The Inheritance Wrap-Up
    5. Metaclass Methods
      1. Metaclass Methods Versus Class Methods
      2. Operator Overloading in Metaclass Methods
      3. Metaclass Methods Versus Instance Methods
    6. Chapter Summary
    7. Test Your Knowledge: Quiz
    8. Test Your Knowledge: Answers
  50. 41. All Good Things
    1. The Python Tsunami
    2. The Python Sandbox
    3. The Python Upside
    4. Closing Thoughts
    5. Where to Go From Here
    6. Encore: Print Your Own Completion Certificate!
  51. IX. Appendixes
  52. A. Platform Usage Tips
    1. Using Python on Windows
    2. Using Python on macOS
    3. Using Python on Linux
    4. Using Python on Android
    5. Using Python on iOS
    6. Standalone Apps and Executables
    7. Etcetera
  53. B. Solutions to End-of-Part Exercises
    1. Part I, Getting Started
    2. Part II, Objects and Operations
    3. Part III, Statements and Syntax
    4. Part IV, Functions and Generators
    5. Part V, Modules and Packages
    6. Part VI, Classes and OOP
    7. Part VII, Exceptions
  54. About the Author

Product information

  • Title: Learning Python, 6th Edition
  • Author(s): Mark Lutz
  • Release date: May 2025
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781098171308