Inhaltsverzeichnis

Alle Kapitel aufklappen
Alle Kapitel zuklappen
1 Introduction
31
1.1 Why Did We Write This Book?
31
1.2 What Does This Book Provide?
32
1.3 Structure of the Book
32
1.4 How Should You Read This Book?
33
1.5 Sample Programs
34
1.6 Preface to the Second English Edition (2026)
34
1.7 Acknowledgments
35
2 The Python Programming Language
37
2.1 History and Origin
37
2.2 Basic Concepts
38
2.3 Possible Areas of Use and Strengths
39
2.4 Installing Python
40
2.4.1 Installing Anaconda on Windows
41
2.4.2 Installing Anaconda on macOS
42
2.4.3 Installing Anaconda on Linux
42
2.5 Installing Third-Party Modules
43
2.6 Using Python
43
PART I Getting Started with Python
45
3 Getting Started with the Interactive Mode
47
3.1 Integers
47
3.2 Floats
49
3.3 Character Strings
49
3.4 Lists
50
3.5 Dictionaries
51
3.6 Variables
52
3.6.1 The Special Meaning of the Underscore
52
3.6.2 Identifiers
53
3.7 Logical Expressions
53
3.8 Functions and Methods
55
3.8.1 Functions
55
3.8.2 Methods
56
3.9 Screen Outputs
57
3.10 Modules
58
4 The Path to the First Program
61
4.1 Typing, Compiling, and Testing
61
4.1.1 Windows
61
4.1.2 Linux and macOS
62
4.1.3 Shebang
62
4.1.4 Internal Processes
63
4.2 Basic Structure of a Python Program
64
4.2.1 Wrapping Long Lines
66
4.2.2 Joining Multiple Lines
67
4.3 The First Program
67
4.3.1 Initialization
68
4.3.2 Loop Header
69
4.3.3 Loop Body
69
4.3.4 Screen Output
69
4.4 Comments
69
4.5 In Case of Error
70
5 Control Structures
73
5.1 Conditionals
73
5.1.1 The if Statement
73
5.1.2 Conditional Expressions
76
5.2 Loops
77
5.2.1 The while Loop
77
5.2.2 Termination of a Loop
77
5.2.3 Detecting a Loop Break
78
5.2.4 Aborting the Current Iteration
79
5.2.5 The for Loop
81
5.3 The pass Statement
84
5.4 Assignment Expressions
84
5.4.1 Motivation
85
5.4.2 The Guessing Numbers Game with Assignment Expressions
86
6 Files
89
6.1 Data Streams
89
6.2 Reading Data from a File
90
6.2.1 Opening and Closing a File
90
6.2.2 The with Statement
91
6.2.3 Reading the File Content
92
6.3 Writing Data to a File
94
6.4 Generating the File Object
95
6.4.1 The Built-In open Function
96
6.4.2 Attributes and Methods of a File Object
97
6.4.3 Changing the Write/Read Position
98
7 The Data Model
101
7.1 The Structure of Instances
103
7.1.1 Data Type
103
7.1.2 Value
105
7.1.3 Identity
106
7.2 Deleting References
107
7.3 Mutable Versus Immutable Data Types
109
7.3.1 Mutable Data Types and Side Effects
110
8 Functions, Methods, and Attributes
113
8.1 Parameters of Functions and Methods
113
8.1.1 Positional Parameters
114
8.1.2 Keyword Arguments
114
8.1.3 Optional Parameters
115
8.1.4 Keyword-Only Parameters
115
8.2 Attributes
116
9 Sources of Information on Python
117
9.1 The Built-In Help Function
117
9.2 The Online Documentation
118
9.3 PEPs
118
PART II Data Types
121
10 Basic Data Types: An Overview
123
10.1 Nothingness: NoneType
124
10.2 Operators
125
10.2.1 Operator Precedence
125
10.2.2 Evaluation Order
127
10.2.3 Concatenating Comparisons
127
11 Numeric Data Types
129
11.1 Arithmetic Operators
129
11.1.1 Augmented Assignments
130
11.2 Comparison Operators
131
11.3 Conversion between Numeric Data Types
132
11.4 Integers: int
133
11.4.1 Numeral Systems
133
11.4.2 Bit Operations
135
11.4.3 The bit_length Method
139
11.5 Floats: float
139
11.5.1 Exponential Notation
140
11.5.2 Precision
140
11.5.3 Infinite and Not a Number
141
11.6 Boolean Values: bool
142
11.6.1 Logical Operators
142
11.6.2 Truth Values of Non-Boolean Data Types
145
11.6.3 Evaluating Logical Operators
146
11.7 Complex Numbers: complex
147
12 Sequential Data Types
151
12.1 The Difference Between Text and Binary Data
151
12.2 Operations on Instances of Sequential Data Types
152
12.2.1 Checking for Elements
153
12.2.2 Concatenation
155
12.2.3 Repetition
156
12.2.4 Indexing
157
12.2.5 Slicing
158
12.2.6 Length of a Sequence
162
12.2.7 The Smallest and the Largest Element
162
12.2.8 Searching for an Element
163
12.2.9 Counting Elements
164
12.3 The list Data Type
164
12.3.1 Changing a Value Within the List: Assignment via []
165
12.3.2 Replacing Sublists and Inserting New Elements: Assignment via []
165
12.3.3 Deleting Elements and Sublists: del in Combination with []
166
12.3.4 Methods of list Instances
166
12.3.5 Sorting Lists: s.sort([key, reverse])
169
12.3.6 Side Effects
172
12.3.7 List Comprehensions
175
12.4 Immutable Lists: tuple
177
12.4.1 Packing and Unpacking
178
12.4.2 Immutable Doesn’t Necessarily Mean Unchangeable!
180
12.5 Strings: str, bytes, bytearray
180
12.5.1 Control Characters
183
12.5.2 Splitting Strings
185
12.5.3 Searching for Substrings
187
12.5.4 Replacing Substrings
188
12.5.5 Removing Prefixes and Suffixes
191
12.5.6 Aligning Strings
192
12.5.7 String Tests
193
12.5.8 Concatenating Elements in Sequential Data Types
194
12.5.9 Formatting Strings
195
12.5.10 Character Sets and Special Characters
206
12.5.11 Template Strings
214
13 Mappings and Sets
217
13.1 Dictionary: dict
217
13.1.1 Creating a Dictionary
217
13.1.2 Keys and Values
218
13.1.3 Iteration
220
13.1.4 Operators
221
13.1.5 Methods
223
13.1.6 Dict Comprehensions
229
13.2 Sets: set and frozenset
229
13.2.1 Creating a Set
229
13.2.2 Iteration
231
13.2.3 Operators
232
13.2.4 Methods
237
13.2.5 Mutable Sets: set
238
13.2.6 Immutable Sets: frozenset
240
14 Collections
243
14.1 Chained Dictionaries
243
14.2 Counting Frequencies
244
14.2.1 d.elements()
245
14.2.2 d.most_common([n])
245
14.2.3 d.subtract([iterable])
246
14.2.4 d.update([iterable])
246
14.3 Dictionaries with Default Values
246
14.4 Doubly Linked Lists
247
14.5 Named Tuples
249
14.5.1 namedtuple(typename, field_names, {rename})
249
15 Date and Time
251
15.1 Elementary Time Functions: time
251
15.1.1 The struct_time Data Type
252
15.1.2 Constants
253
15.1.3 Functions
254
15.2 Object-Oriented Date Management: datetime
259
15.2.1 datetime.date
259
15.2.2 datetime.time
261
15.2.3 datetime.datetime
261
15.2.4 datetime.timedelta
264
15.2.5 Operations for datetime.datetime and datetime.date
266
15.3 Time Zones: zoneinfo
268
15.3.1 The IANA Time Zone Database
268
15.3.2 Specifying the Time in Local Time Zones
269
15.3.3 Calculating with Time Indications in Local Time Zones
270
16 Enumerations and Flags
273
16.1 Enumeration Types: enum
273
16.2 Enumeration Types for Bit Patterns: Flag
275
16.3 Integer Enumeration Types: IntEnum
276
PART III Advanced Programming Techniques
277
17 Functions
279
17.1 Defining a Function
280
17.2 Return Values
282
17.3 Function Objects
284
17.4 Optional Parameters
284
17.5 Keyword Arguments
285
17.6 Arbitrarily Many Parameters
286
17.7 Keyword-Only Parameters
288
17.8 Positional-Only Parameters
289
17.9 Unpacking When Calling a Function
290
17.10 Side Effects
293
17.11 Namespaces
295
17.11.1 Accessing Global Variables: global
295
17.11.2 Accessing the Global Namespace
296
17.11.3 Local Functions
297
17.11.4 Accessing Parent Namespaces: nonlocal
298
17.11.5 Unbound Local Variables: A Stumbling Block
300
17.12 Anonymous Functions
301
17.13 Recursion
302
17.14 Built-In Functions
303
17.14.1 abs(x)
306
17.14.2 all(iterable)
306
17.14.3 any(iterable)
307
17.14.4 ascii(object)
307
17.14.5 bin(x)
307
17.14.6 bool([x])
307
17.14.7 bytearray([source, encoding, errors])
308
17.14.8 bytes([source, encoding, errors])
308
17.14.9 chr(i)
309
17.14.10 complex([real, imag])
309
17.14.11 dict([source])
310
17.14.12 divmod(a, b)
310
17.14.13 enumerate(iterable, [start])
310
17.14.14 eval(expression, [globals, locals])
311
17.14.15 exec(object, [globals, locals])
312
17.14.16 filter(function, iterable)
312
17.14.17 float([x])
312
17.14.18 format(value, [format_spec])
313
17.14.19 frozenset([iterable])
313
17.14.20 globals()
314
17.14.21 hash(object)
314
17.14.22 help([object])
315
17.14.23 hex(x)
315
17.14.24 id(object)
315
17.14.25 input([prompt])
315
17.14.26 int([x, base])
316
17.14.27 len(s)
316
17.14.28 list([sequence])
317
17.14.29 locals()
317
17.14.30 map(function, [*iterable, strict])
317
17.14.31 max(iterable, {default, key}), max(arg1, arg2, [*args], {key})
319
17.14.32 min(iterable, {default, key}), min(arg1, arg2, [*args], {key})
320
17.14.33 oct(x)
320
17.14.34 ord(c)
320
17.14.35 pow(x, y, [z])
320
17.14.36 print([*objects], {sep, end, file, flush})
320
17.14.37 range([start], stop, [step])
321
17.14.38 repr(object)
322
17.14.39 reversed(sequence)
322
17.14.40 round(x, [n])
323
17.14.41 set([iterable])
323
17.14.42 sorted(iterable, [key, reverse])
323
17.14.43 str([object, encoding, errors])
324
17.14.44 sum(iterable, [start])
325
17.14.45 tuple([iterable])
325
17.14.46 type(object)
325
17.14.47 zip([*iterables], {strict})
326
18 Modules and Packages
327
18.1 Importing Global Modules
328
18.2 Local Modules
330
18.2.1 Name Conflicts
331
18.2.2 Module-Internal References
332
18.2.3 Executing Modules
332
18.3 Packages
332
18.3.1 Importing All Modules of a Package
334
18.3.2 Namespace Packages
335
18.3.3 Relative Import Statements
336
18.4 The importlib Package
336
18.5 Planned Language Elements
337
19 Object-Oriented Programming
339
19.1 Example: A Non-Object-Oriented Account
339
19.1.1 Creating a New Account
340
19.1.2 Transferring Money
340
19.1.3 Depositing and Withdrawing Money
341
19.1.4 Viewing the Account Balance
341
19.2 Classes
344
19.2.1 Defining Methods
345
19.2.2 The Constructor
346
19.2.3 Attributes
347
19.2.4 Example: An Object-Oriented Account
347
19.3 Inheritance
349
19.3.1 A Simple Example
349
19.3.2 Overriding Methods
350
19.3.3 Example: Checking Account with Daily Turnover
353
19.3.4 Outlook
361
19.4 Multiple Inheritance
361
19.4.1 Potential Pitfalls of Multiple Inheritance
362
19.5 Property Attributes
363
19.5.1 Setters and Getters
363
19.5.2 Defining Property Attributes
364
19.6 Static Methods
365
19.6.1 Defining Static Methods
366
19.7 Class Methods
367
19.8 Class Attributes
368
19.9 Built-in Functions for Object-Oriented Programming
369
19.9.1 Functions for Managing the Attributes of an Instance
370
19.9.2 Functions for Information About the Class Hierarchy
371
19.10 Inheriting Built-In Data Types
372
19.11 Magic Methods and Magic Attributes
374
19.11.1 General Magic Methods
374
19.11.2 Overloading Operators
382
19.11.3 Emulating Data Types: Duck Typing
388
19.12 Data Classes
393
19.12.1 Tuples and Lists
393
19.12.2 Dictionaries
394
19.12.3 Named Tuples
394
19.12.4 Mutable Data Classes
395
19.12.5 Immutable Data Classes
396
19.12.6 Default Values in Data Classes
396
20 Exception Handling
399
20.1 Exceptions
399
20.1.1 Built-In Exceptions
400
20.1.2 Raising an Exception
401
20.1.3 Handling an Exception
401
20.1.4 Custom Exceptions
406
20.1.5 Reraising an Exception
408
20.1.6 Exception Chaining
411
20.1.7 Exception Notes
412
20.2 Assertions
414
20.3 Warnings
415
20.4 Exception Groups
416
20.4.1 An Exception Group
416
20.4.2 The try/except* Statement
418
21 Generators and Iterators
421
21.1 Generators
421
21.1.1 Subgenerators
424
21.1.2 Generator Expressions
427
21.2 Iterators
428
21.2.1 The Iterator Protocol
428
21.2.2 Example: The Fibonacci Sequence
428
21.2.3 Example: The Golden Ratio
430
21.2.4 A Generator for the Implementation of __iter__
430
21.2.5 Using Iterators
431
21.2.6 Multiple Iterators for the Same Instance
434
21.2.7 Disadvantages of Iterators Compared to Direct Access via Indexes
436
21.2.8 Alternative Definition for Iterable Objects
436
21.2.9 Function Iterators
437
21.3 Special Generators: itertools
437
21.3.1 accumulate(iterable, [func])
439
21.3.2 batched(iterable, n, {strict})
439
21.3.3 chain([*iterables])
440
21.3.4 combinations(iterable, r)
440
21.3.5 combinations_with_replacement(iterable, r)
441
21.3.6 compress(data, selectors)
441
21.3.7 count([start, step])
441
21.3.8 cycle(iterable)
442
21.3.9 dropwhile(predicate, iterable)
442
21.3.10 filterfalse(predicate, iterable)
442
21.3.11 groupby(iterable, [key])
443
21.3.12 islice(iterable, [start], stop, [step])
444
21.3.13 permutations(iterable, [r])
444
21.3.14 product([*iterables], [repeat])
444
21.3.15 repeat(object, [times])
445
21.3.16 starmap(function, iterable)
445
21.3.17 takewhile(predicate, iterable)
445
21.3.18 tee(iterable, [n])
446
21.3.19 zip_longest([*iterables], {fillvalue})
446
21.4 Generators as Consumers
446
21.4.1 Triggering Exceptions in a Generator
448
21.4.2 An Example Application for Consuming Generator Functions
449
22 Context Manager
453
22.1 The with Statement
453
22.1.1 __enter__(self)
455
22.1.2 __exit__(self, exc_type, exc_value, traceback)
455
22.2 Helper Functions for with Contexts: contextlib
456
22.2.1 Dynamically Assembled Context Combinations: ExitStack
456
22.2.2 Suppressing Certain Exception Types
457
22.2.3 Redirecting the Standard Output Stream
457
22.2.4 Optional Contexts
458
22.2.5 Simple Functions as Context Manager
458
22.2.6 Temporarily Changing the Working Directory
459
23 Decorators
461
23.1 Function Decorators
461
23.1.1 Decorating Functions and Methods
463
23.1.2 Name and Docstring after Applying a Decorator
463
23.1.3 Nested Decorators
464
23.1.4 Example: A Cache Decorator
464
23.2 Class Decorators
466
23.3 The functools Module
467
23.3.1 Simplifying Function Interfaces
467
23.3.2 Simplifying Method Interfaces
468
23.3.3 Caches
469
23.3.4 Completing Orderings of Custom Classes
470
23.3.5 Overloading Functions
471
24 Annotations for Static Type Checking
473
24.1 Annotations
474
24.1.1 Annotating Functions and Methods
475
24.1.2 Annotating Variables and Attributes
476
24.1.3 Accessing Annotations at Runtime
478
24.1.4 When Are Annotations Evaluated?
479
24.2 Type Hints: The typing Module
481
24.2.1 Valid Type Hints
482
24.2.2 Container Types
482
24.2.3 Abstract Container Types
483
24.2.4 Type Aliases
483
24.2.5 Type Unions and Optional Values
484
24.2.6 Literals
485
24.2.7 Type Variables
486
24.3 Static Type Checking in Python: mypy
487
24.3.1 Installation
487
24.3.2 Example
487
25 Structural Pattern Matching
489
25.1 The match Statement
489
25.2 Pattern Types in the case Statement
490
25.2.1 Literal and Value Patterns
490
25.2.2 OR Pattern
491
25.2.3 Patterns with Type Checking
492
25.2.4 Specifying Conditions for Matches
492
25.2.5 Grouping Subpatterns
493
25.2.6 Capture and Wildcard Patterns
493
25.2.7 Sequence Patterns
495
25.2.8 Mapping Patterns
497
25.2.9 Patterns for Objects and Their Attribute Values
500
PART IV The Standard Library
505
26 Mathematics
507
26.1 Mathematical Functions: math, cmath
507
26.1.1 General Mathematical Functions
508
26.1.2 Exponential and Logarithm Functions
511
26.1.3 Trigonometric and Hyperbolic Functions
511
26.1.4 Distances and Norms
512
26.1.5 Converting Angles
512
26.1.6 Representations of Complex Numbers
513
26.2 Random Number Generator: random
513
26.2.1 Saving and Loading the Random State
514
26.2.2 Generating Random Integers
514
26.2.3 Generating Random Floats
515
26.2.4 Random Operations on Sequences
515
26.2.5 SystemRandom([seed])
517
26.3 Statistical Calculations: statistics
517
26.4 Intuitive Decimal Numbers: decimal
518
26.4.1 Using the Data Type
519
26.4.2 Nonnumeric Values
522
26.4.3 The Context Object
523
26.5 Hash Functions: hashlib
524
26.5.1 Using the Module
526
26.5.2 Other Hash Algorithms
527
26.5.3 Comparing Large Files
527
26.5.4 Passwords
528
27 Screen Outputs and Logging
531
27.1 Formatted Output of Complex Objects: pprint
531
27.1.1 pprint(object, [stream, indent, width, depth], {compact})
531
27.2 Log Files: logging
533
27.2.1 Customizing the Message Format
535
27.2.2 Logging Handlers
537
28 Regular Expressions
539
28.1 Syntax of Regular Expressions
539
28.1.1 Any Character
539
28.1.2 Character Classes
540
28.1.3 Quantifiers
541
28.1.4 Predefined Character Classes
543
28.1.5 Other Special Characters
544
28.1.6 Nongreedy Quantifiers
545
28.1.7 Groups
546
28.1.8 Alternatives
546
28.1.9 Extensions
546
28.2 Using the re Module
549
28.2.1 Searching
549
28.2.2 Matching
550
28.2.3 Splitting a String
550
28.2.4 Replacing Parts of a String
551
28.2.5 Replacing Problem Characters
552
28.2.6 Compiling a Regular Expression
552
28.2.7 Flags
552
28.2.8 The Match Object
554
28.3 A Simple Sample Program: Searching
555
28.4 A More Complex Sample Program: Matching
556
28.5 Comments in Regular Expressions
559
28.6 Catastrophic Backtracking
560
29 Interface to Operating System and Runtime Environment
563
29.1 Operating System Functionality: os
563
29.1.1 environ
564
29.1.2 getpid()
564
29.1.3 cpu_count()
564
29.1.4 system(cmd)
564
29.1.5 popen(command, [mode, buffering])
565
29.2 Starting Subprocesses: subprocess
565
29.2.1 Starting a Subprocess
566
29.2.2 The Default Streams: stdin, stdout, and stderr
567
29.2.3 The Return Code
568
29.2.4 Environment variables
568
29.3 Accessing the Runtime Environment: sys
568
29.3.1 Command Line Parameters
569
29.3.2 Default Paths
569
29.3.3 Standard Input/Output Streams
569
29.3.4 Exiting the Program
569
29.3.5 Details of the Python Version
570
29.3.6 Operating System Details
570
29.3.7 Hooks
571
29.4 Command Line Parameters: argparse
573
29.4.1 Calculator: A Simple Example
574
29.4.2 A More Complex Example
578
30 File System
581
30.1 Basics of File Systems and Paths
581
30.1.1 Path Names
581
30.1.2 File Names
582
30.1.3 Absolute and Relative Paths
582
30.1.4 Access Rights
582
30.2 The Modern Approach: pathlib
583
30.2.1 The Path Class
583
30.2.2 Combining Paths
584
30.2.3 Attributes of a Path
584
30.2.4 Checking Path Properties
585
30.2.5 Reading and Writing Files
585
30.2.6 Renaming Files
586
30.2.7 Copying and Moving Files
586
30.2.8 Deleting Files
587
30.2.9 Creating and Deleting Directories
587
30.2.10 Links
588
30.2.11 Globbing
588
30.3 Accessing the File System: os
589
30.3.1 access(path, mode)
591
30.3.2 chmod(path, mode)
591
30.3.3 listdir([path])
592
30.3.4 mkdir(path, [mode]) and makedirs(path, [mode])
592
30.3.5 remove(path)
593
30.3.6 removedirs(path)
593
30.3.7 rename(src, dst) and renames(old, new)
593
30.3.8 walk(top, [topdown, onerror])
594
30.4 File Paths: os.path
595
30.4.1 abspath(path)
597
30.4.2 basename(path)
597
30.4.3 commonprefix(list)
598
30.4.4 dirname(path)
598
30.4.5 join(path, *paths)
598
30.4.6 normcase(path)
599
30.4.7 split(path)
599
30.4.8 splitdrive(path)
599
30.4.9 splitext(path)
600
30.5 Accessing the File System: shutil
600
30.5.1 Directory and File Operations
602
30.5.2 Archive Operations
603
30.6 Temporary Files: tempfile
605
30.6.1 TemporaryFile([mode, [bufsize, suffix, prefix, dir])
605
30.6.2 TemporaryDirectory([suffix, prefix, dir])
606
31 Parallel Programming
607
31.1 Processes, Multitasking, and Threads
607
31.1.1 The Lightweights Among the Processes: Threads
608
31.1.2 The Global Interpreter Lock
609
31.1.3 Threads or Processes?
610
31.1.4 Cooperative Multitasking
610
31.2 Python's Interfaces for Parallelization
611
31.3 The Abstract Interface: concurrent.futures
612
31.3.1 An Example with a futures.ThreadPoolExecutor
612
31.3.2 Executor Instances as Context Managers
614
31.3.3 Using futures.ProcessPoolExecutor
615
31.3.4 Managing the Tasks of an Executor
616
31.4 The Flexible Interface: threading and multiprocessing
622
31.4.1 Threads in Python: threading
622
31.4.2 Processes in Python: multiprocessing
631
31.5 Cooperative Multitasking
633
31.5.1 Cooperative Functions: Coroutines
633
31.5.2 Awaitable Objects
634
31.5.3 The Cooperation of Coroutines: Tasks
635
31.5.4 A Cooperative Web Crawler
637
31.5.5 Blocking Operations in Coroutines
645
31.5.6 Other Asynchronous Language Features
646
31.6 Conclusion: Which Interface Is the Right One?
649
31.6.1 Is Cooperative Multitasking an Option?
650
31.6.2 Abstraction or Flexibility?
650
31.6.3 Threads or Processes?
650
32 Data Storage
651
32.1 The JSON Data Exchange Format: json
651
32.2 Serializing Instances: pickle
652
32.2.1 Functional Interface
654
32.2.2 Object-Oriented Interface
655
32.3 The CSV Table Format: csv
656
32.3.1 Reading Data from a CSV File with reader Objects
657
32.3.2 Using Custom Dialects: Dialect Objects
659
32.4 Compressed Files and Archives
661
32.4.1 gzip.open(filename, [mode, compresslevel])
662
32.4.2 Other Modules for Accessing Compressed Data
662
32.5 Databases
663
32.5.1 The Built-In Database in Python: sqlite3
666
32.6 XML
681
32.6.1 ElementTree
683
32.6.2 SAX
690
33 Network Communication
695
33.1 Socket API
696
33.1.1 Client-Server Systems
697
33.1.2 UDP
699
33.1.3 TCP
700
33.1.4 Blocking and Nonblocking Sockets
702
33.1.5 Creating a Socket
703
33.1.6 The Socket Class
704
33.1.7 Network Byte Order
707
33.1.8 Multiplexing Servers: selectors
708
33.1.9 Object-Oriented Server Development: socketserver
710
33.2 XML-RPC
712
33.2.1 The Server
713
33.2.2 The Client
716
33.2.3 Multicall
717
33.2.4 Limitations
718
34 Accessing Resources on the Internet
721
34.1 Protocols
721
34.1.1 Hypertext Transfer Protocol
721
34.1.2 File Transfer Protocol
721
34.2 Solutions
722
34.2.1 Outdated Solutions for Python 2
722
34.2.2 Solutions in the Standard Library
722
34.2.3 Third-Party Solutions
722
34.3 The Easy Way: requests
722
34.3.1 Simple Requests via GET and POST
723
34.3.2 Web APIs
724
34.4 URLs: urllib
725
34.4.1 Accessing Remote Resources: urllib.request
726
34.4.2 Reading and Processing URLs: urllib.parse
729
34.5 FTP: ftplib
733
34.5.1 Connecting to an FTP Server
734
34.5.2 Executing FTP commands
735
34.5.3 Working with Files and Directories
735
34.5.4 Transferring Files
736
35 Email
739
35.1 SMTP: smtplib
739
35.1.1 SMTP([host, port, local_hostname, timeout, source_address])
740
35.1.2 Establishing and Terminating a Connection
740
35.1.3 Sending an Email
741
35.1.4 Example
741
35.2 POP3: poplib
742
35.2.1 POP3(host, [port, timeout])
743
35.2.2 Establishing and Terminating a Connection
743
35.2.3 Listing Existing Emails
744
35.2.4 Retrieving and Deleting Emails
744
35.2.5 Example
745
35.3 IMAP4: imaplib
746
35.3.1 IMAP4([host, port, timeout])
746
35.3.2 Establishing and Terminating a Connection
747
35.3.3 Finding and Selecting a Mailbox
748
35.3.4 Operations with Mailboxes
749
35.3.5 Searching Emails
749
35.3.6 Retrieving Emails
749
35.3.7 Example
750
35.4 Creating Complex Emails: email
751
35.4.1 Creating a Simple Email
751
35.4.2 Creating an Email with Attachments
752
35.4.3 Reading an Email
754
36 Debugging and Quality Assurance
755
36.1 The Debugger
755
36.2 Automated Testing
757
36.2.1 Test Cases in Docstrings: doctest
758
36.2.2 Unit Tests: unittest
762
36.3 Analyzing the Runtime Performance
765
36.3.1 Runtime Measurement: timeit
765
36.3.2 Profiling: cProfile
768
36.3.3 Tracing: trace
772
37 Documentation
775
37.1 Docstrings
775
37.2 Automatically Generated Documentation: pydoc
777
PART V Advanced Topics
779
38 Distributing Python Projects
781
38.1 A History of Distributions in Python
781
38.1.1 The Classic Approach: distutils
781
38.1.2 The New Standard: setuptools
782
38.1.3 The Package Index: PyPI
782
38.2 Creating Distributions: setuptools
782
38.2.1 Installation
783
38.2.2 Writing the Module
783
38.2.3 The Installation Script
784
38.2.4 Creating a Source Distribution
788
38.2.5 Creating a Binary Distribution
789
38.2.6 Installing Distributions
790
38.3 Creating EXE files: cx_Freeze
790
38.3.1 Installation
791
38.3.2 Usage
791
38.4 Package Manager
792
38.4.1 The Python Package Manager: pip
793
38.4.2 The conda Package Manager
794
38.5 Localizing Programs: gettext
797
38.5.1 Example of Using gettext
797
38.5.2 Creating the Language Compilation
799
39 Virtual Environments
801
39.1 Using Virtual Environments: venv
802
39.1.1 Activating a Virtual Environment
802
39.1.2 Working in a Virtual Environment
802
39.1.3 Deactivating a Virtual Environment
803
39.2 Virtual Environments in Anaconda
803
40 Alternative Interpreters and Compilers
805
40.1 Just-in-Time Compilation: PyPy
805
40.1.1 Installation and Use
806
40.1.2 Example
806
40.2 Numba
806
40.2.1 Installation
807
40.2.2 Example
807
40.3 Connecting to C and C++: Cython
809
40.3.1 Installation
809
40.3.2 The Functionality of Cython
810
40.3.3 Compiling a Cython Program
810
40.3.4 A Cython Program with Static Typing
812
40.3.5 Using a C Library
813
40.4 The Interactive Python Shell: IPython
815
40.4.1 Installation
815
40.4.2 The Interactive Shell
815
40.4.3 The Jupyter Notebook
818
41 Graphical User Interfaces
823
41.1 Toolkits
823
41.1.1 Tkinter (Tk)
823
41.1.2 PyGObject (GTK)
824
41.1.3 Qt for Python (Qt)
824
41.1.4 wxPython (wxWidgets)
824
41.2 Introduction to tkinter
825
41.2.1 A Simple Example
825
41.2.2 Control Variables
827
41.2.3 The Packer
829
41.2.4 Events
833
41.2.5 Widgets
838
41.2.6 Drawings: The Canvas Widget
856
41.2.7 Other Modules
863
41.3 Introduction to PySide6
866
41.3.1 Installation
867
41.3.2 Basic Concepts of Qt
867
41.3.3 Development Process
869
41.3.4 Signals and Slots
875
41.3.5 Important Widgets
878
41.3.6 Drawing Functionality
884
41.3.7 Model-View Architecture
896
42 Python as a Server-Side Programming Language on the Web: An Introduction to Django
911
42.1 Concepts and Features of Django
912
42.2 Installing Django
913
42.3 Creating a New Django Project
914
42.3.1 The Development Web Server
915
42.3.2 Configuring the Project
916
42.4 Creating an Application
917
42.4.1 Importing the Application into the Project
919
42.4.2 Defining a Model
919
42.4.3 Relationships between Models
920
42.4.4 Transferring the Model to the Database
921
42.4.5 The Model API
922
42.4.6 The Project Gets a Face
927
42.4.7 Django's Template System
933
42.4.8 Processing Form Data
944
42.4.9 Django’s Admin Control Panel
947
43 Scientific Computing and Data Science
953
43.1 Installation
954
43.2 The Model Program
954
43.2.1 Importing numpy, scipy, and matplotlib
955
43.2.2 Vectorization and the numpy.ndarray Data Type
956
43.2.3 Visualizing Data Using matplotlib.pyplot
959
43.3 Overview of the numpy and scipy Modules
962
43.3.1 Overview of the numpy.ndarray Data Type
962
43.3.2 Overview of scipy
970
43.4 An Introduction to Data Analysis with pandas
971
43.4.1 The DataFrame Object
972
43.4.2 Selective Data Access
974
43.4.3 Deleting Rows and Columns
979
43.4.4 Inserting Rows and Columns
979
43.4.5 Logical Expressions on Data Records
980
43.4.6 Manipulating Data Records
981
43.4.7 Input and Output
983
43.4.8 Visualization
984
44 Inside Knowledge
987
44.1 Opening URLs in the Default Browser: webbrowser
987
44.1.1 open(url, [new, autoraise])
987
44.2 Interpreting Binary Data: struct
987
44.3 Hidden Password Entry
989
44.3.1 getpass([prompt, stream], {echo_char})
990
44.3.2 getpass.getuser()
990
44.4 Command Line Interpreter
990
44.5 File Interface for Strings: io.StringIO
993
44.6 Copying Instances: copy
994
44.6.1 Back to the Initial Example
996
44.7 Image Processing: Pillow
997
44.7.1 Installation
997
44.7.2 Loading and Saving Image Files
997
44.7.3 Accessing Individual Pixels
998
44.7.4 Manipulating Images
999
44.7.5 Interoperability
1005
45 A History of Python Versions
1007
45.1 Python’s Version History
1007
45.2 The Leap to Python 3
1010
45.2.1 Input/Output
1011
45.2.2 Iterators
1012
45.2.3 Strings
1012
45.2.4 Integers
1013
45.2.5 Exception Handling
1014
45.2.6 Standard Library
1014
A Appendix
1017
A.1 Reserved Words
1017
A.2 Operator Precedence
1017
A.3 Built-In Functions
1019
A.4 Built-In Exceptions
1023
A.5 Python IDEs
1027
A.5.1 PyCharm
1027
A.5.2 Visual Studio Code
1028
A.5.3 Spyder
1028
The Authors
1029
Index
1031