Python in a Nutshell, 4th Edition (Alex Martelli, Anna Martelli Ravenscroft etc.) (Z-Library)

Author: Alex Martelli, Anna Martelli Ravenscroft, Steve Holden, Paul McGuire

科学

Python was recently ranked as today's most popular programming language on the TIOBE index, thanks to its broad applicability to design and prototyping to testing, deployment, and maintenance. With this updated fourth edition, you'll learn how to get the most out of Python, whether you're a professional programmer or someone who needs this language to solve problems in a particular field. Carefully curated by recognized experts in Python, this new edition focuses on version 3.10, bringing this seminal work on the Python language fully up to date on five version releases, including preview coverage of upcoming 3.11 features. This handy guide will help you: • Learn how Python represents data and program as objects • Understand the value and uses of type annotations • Examine which language features appeared in which recent versions • Discover how to use modern Python idiomatically • Learn ways to structure Python projects appropriately • Understand how to debug Python code

📄 File Format: PDF
💾 File Size: 5.8 MB
23
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
Alex Martelli, Anna Martelli Ravenscroft, Steve Holden & Paul McGuire Python in a Nutshell A Desktop Quick Reference 4th Edition Covers Python 3.7 through 3.11
📄 Page 2
PROGR AMMING Python in a Nutshell US $89.99 CAN $112.99 ISBN: 978-1-098-11355-1 Python was recently ranked as today’s most popular programming language on the TIOBE index, thanks, especially, to its broad applicability to design, prototyping, testing, deployment, and maintenance. With this updated fourth edition, you’ll learn how to get the most out of Python, whether you’re a professional programmer or someone who needs this language to solve problems in a particular field. Carefully curated by recognized experts in Python, this new edition focuses on version 3.10, bringing this seminal work on the Python language fully up to date on five version releases, including coverage of recently released Python 3.11. This handy guide will help you: • Learn how Python represents data and program as objects • Understand the value and uses of type annotations • Examine which language features appeared in which recent versions • Discover how to use modern Python idiomatically • Learn ways to structure Python projects appropriately • Understand how to test, debug, and optimize Python code The authors are four PSF Fellows, three of whom are Frank Willison Award recipients, recognized for numerous contributions to Python and its community. Their collective experience covers environments and platforms ranging from academic to startup to corporate to government. Together they have compiled an authoritative reference for Python language syntax and features, the Python standard library, and selected third-party packages. “Python in depth, up-to-date, accessible, and useful. An excellent modern reference with plenty of insight and advice that will satisfy everyone from early intermediates to experts.” —Mark Summerfield Director of Qtrac Ltd. Twitter: @oreillymedia linkedin.com/company/oreilly-media youtube.com/oreillymedia
📄 Page 3
PYTHON IN A NUTSHELL A Desktop Quick Reference Fourth Edition Alex Martelli, Anna Martelli Ravenscroft, Steve Holden, and Paul McGuire
📄 Page 4
978-1-098-11355-1 [LSI] Python in a Nutshell by Alex Martelli, Anna Martelli Ravenscroft, Steve Holden, and Paul McGuire Copyright © 2023 Alex Martelli, Anna Martelli Ravenscroft, Steve Holden, and Paul McGuire. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Brian Guerin Development Editor: Angela Rufino Production Editor: Christopher Faucher Copyeditor: Rachel Head Proofreader: Sonia Saruba Indexer: Judith McConville Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: O’Reilly Media, Inc. March 2003: First Edition July 2006: Second Edition April 2017: Third Edition January 2023: Fourth Edition Revision History for the Fourth Edition 2023-01-09: First Release See https://www.oreilly.com/catalog/errata.csp?isbn=0636920602804 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Python in a Nutshell, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the authors have used good faith efforts to ensure that the informa‐ tion and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other tech‐ nology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
📄 Page 5
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. Introduction to Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 The Python Language 1 The Python Standard Library and Extension Modules 2 Python Implementations 3 Python Development and Versions 10 Python Resources 11 Installation 14 Installing Python from Binaries 15 Installing Python from Source Code 16 2. The Python Interpreter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 The python Program 21 Python Development Environments 27 Running Python Programs 29 Running Python in the Browser 30 3. The Python Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Lexical Structure 33 Data Types 40 Variables and Other References 52 Expressions and Operators 57 Numeric Operations 60 Sequence Operations 62 iii
📄 Page 6
Set Operations 69 Dictionary Operations 71 Control Flow Statements 73 Functions 93 4. Object-Oriented Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Classes and Instances 115 Special Methods 141 Decorators 157 Metaclasses 158 5. Type Annotations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 History 171 Type-Checking Utilities 173 Type Annotation Syntax 174 The typing Module 176 Using Type Annotations at Runtime 191 How to Add Type Annotations to Your Code 192 Summary 194 6. Exceptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 The try Statement 195 The raise Statement 200 The with Statement and Context Managers 201 Generators and Exceptions 203 Exception Propagation 204 Exception Objects 205 Custom Exception Classes 210 ExceptionGroup and except* 212 Error-Checking Strategies 214 The assert Statement 219 7. Modules and Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Module Objects 222 Module Loading 227 Packages 233 Distribution Utilities (distutils) and setuptools 235 Python Environments 237 iv | Table of Contents
📄 Page 7
8. Core Built-ins and Standard Library Modules. . . . . . . . . . . . . . . . . . . . . . . . . 247 Built-in Types 247 Built-in Functions 251 The sys Module 259 The copy Module 263 The collections Module 264 The functools Module 269 The heapq Module 271 The argparse Module 274 The itertools Module 275 9. Strings and Things. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 Methods of String Objects 281 The string Module 286 String Formatting 287 Text Wrapping and Filling 300 The pprint Module 300 The reprlib Module 301 Unicode 301 10. Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Regular Expressions and the re Module 305 Optional Flags 311 Match Versus Search 313 Anchoring at String Start and End 313 Regular Expression Objects 314 Match Objects 317 Functions of the re Module 318 REs and the := Operator 319 The Third-Party regex Module 320 11. File and Text Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 The io Module 322 The tempfile Module 328 Auxiliary Modules for File I/O 330 In-Memory Files: io.StringIO and io.BytesIO 334 Archived and Compressed Files 335 The os Module 343 Table of Contents | v
📄 Page 8
The errno Module 357 The pathlib Module 357 The stat Module 362 The filecmp Module 363 The fnmatch Module 365 The glob Module 366 The shutil Module 366 Text Input and Output 368 Richer-Text I/O 371 Internationalization 374 12. Persistence and Databases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383 Serialization 384 DBM Modules 396 The Python Database API (DBAPI) 399 13. Time Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 The time Module 411 The datetime Module 415 The zoneinfo Module 422 The dateutil Module 424 The sched Module 425 The calendar Module 426 14. Customizing Execution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 Per-Site Customization 429 Termination Functions 430 Dynamic Execution and exec 430 Internal Types 434 Garbage Collection 435 15. Concurrency: Threads and Processes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 Threads in Python 445 The threading Module 446 The queue Module 456 The multiprocessing Module 459 The concurrent.futures Module 468 Threaded Program Architecture 471 Process Environment 475 vi | Table of Contents
📄 Page 9
Running Other Programs 476 The mmap Module 481 16. Numeric Processing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485 Floating-Point Values 485 The math and cmath Modules 488 The statistics Module 493 The operator Module 493 Random and Pseudorandom Numbers 496 The fractions Module 498 The decimal Module 500 Array Processing 502 17. Testing, Debugging, and Optimizing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513 Testing 514 Debugging 528 The warnings Module 538 Optimization 541 18. Networking Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563 The Berkeley Socket Interface 564 Transport Layer Security 579 SSLContext 580 19. Client-Side Network Protocol Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583 Email Protocols 584 HTTP and URL Clients 587 Other Network Protocols 595 20. Serving HTTP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597 http.server 598 WSGI 598 Python Web Frameworks 600 21. Email, MIME, and Other Network Encodings. . . . . . . . . . . . . . . . . . . . . . . . . . 611 MIME and Email Format Handling 611 Encoding Binary Data as ASCII Text 619 22. Structured Text: HTML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623 The html.entities Module 624 Table of Contents | vii
📄 Page 10
The BeautifulSoup Third-Party Package 624 Generating HTML 635 23. Structured Text: XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643 ElementTree 644 Parsing XML with ElementTree.parse 650 Building an ElementTree from Scratch 652 Parsing XML Iteratively 652 24. Packaging Programs and Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655 What We Don’t Cover in This Chapter 656 A Brief History of Python Packaging 657 Online Material 658 25. Extending and Embedding Classic Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . 659 Online Material 660 26. v3.7 to v3.n Migration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661 Significant Changes in Python Through 3.11 662 Planning a Python Version Upgrade 664 Summary 668 Appendix. New Features and Changes in Python 3.7 Through 3.11. . . . . . . . . 669 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 viii | Table of Contents
📄 Page 11
Preface The Python programming language reconciles many apparent contradictions: ele‐ gant yet pragmatic, simple yet powerful, it’s very high-level yet doesn’t get in your way when you need to fiddle with bits and bytes, and it’s suitable for novice programmers and great for experts, too. This book is intended for programmers with some previous exposure to Python, as well as experienced programmers coming to Python for the first time from other languages. It provides a quick reference to Python itself, the most commonly used parts of its vast standard library, and a few of the most popular and useful third- party modules and packages. The Python ecosystem has grown so much in richness, scope, and complexity that a single volume can no longer reasonably hope to be encyclopedic. Still, the book covers a wide range of application areas, including web and network programming, XML handling, database interactions, and high-speed numeric computing. It also explores Python’s cross-platform capabilities and the basics of extending Python and embedding it in other applications. How To Use This Book While you can read this volume linearly from the beginning, we also aim for it to be a useful reference for the working programmer. You may choose to use the index to locate items of interest, or to read specific chapters for coverage of their particular topics. However you use it, we sincerely hope you enjoy reading what represents the fruit of the best part of a year’s work for the team. The book has five parts, as follows. ix
📄 Page 12
Part I, Getting Started with Python Chapter 1, “Introduction to Python” Covers the general characteristics of the Python language, its implementations, where to get help and information, how to participate in the Python commu‐ nity, and how to obtain and install Python on your computer(s) or run it in your browser. Chapter 2, “The Python Interpreter” Covers the Python interpreter program, its command-line options, and how to use it to run Python programs and in interactive sessions. The chapter mentions text editors for editing Python programs and auxiliary programs for checking your Python sources, along with some full-fledged integrated development environments, including IDLE, which comes free with standard Python. The chapter also covers running Python programs from the command line. Part II, Core Python Language and Built-ins Chapter 3, “The Python Language” Covers Python syntax, built-in data types, expressions, statements, control flow, and how to write and call functions. Chapter 4, “Object-Oriented Python” Covers object-oriented programming in Python. Chapter 5, “Type Annotations” Covers how to add type information to your Python code, to gain type hinting and autocomplete help from modern code editors and support static type checking from type checkers and linters. Chapter 6, “Exceptions” Covers how to use exceptions for errors and special situations, logging, and how to write code to automatically clean up when exceptions occur. Chapter 7, “Modules and Packages” Covers how Python lets you group code into modules and packages, how to define and import modules, and how to install third-party Python packages. This chapter also covers working with virtual environments to isolate project dependencies. Chapter 8, “Core Built-ins and Standard Library Modules” Covers built-in data types and functions, and some of the most fundamental modules in the Python standard library (roughly speaking, the set of modules supplying functionality that, in some other languages, is built into the language itself). Chapter 9, “Strings and Things” Covers Python’s facilities for processing strings, including Unicode strings, bytestrings, and string literals. x | Preface
📄 Page 13
1 The separate chapter on asynchronous programming in the third edition has been dropped in this edition, deferring to more thorough coverage of this growing topic in references found in Chapter 15. Chapter 10, “Regular Expressions” Covers Python’s support for regular expressions. Part III, Python Library and Extension Modules Chapter 11, “File and Text Operations” Covers dealing with files and text with many modules from Python’s standard library and platform-specific extensions for rich text I/O. This chapter also covers issues regarding internationalization and localization. Chapter 12, “Persistence and Databases” Covers Python’s serialization and persistence mechanisms and its interfaces to DBM databases and relational (SQL-based) databases, particularly the handy SQLite that comes with Python’s standard library. Chapter 13, “Time Operations” Covers dealing with times and dates in Python, with the standard library and third-party extensions. Chapter 14, “Customizing Execution” Covers ways to achieve advanced execution control in Python, including exe‐ cution of dynamically generated code and control of garbage collection. This chapter also covers some Python internal types, and the specific issue of regis‐ tering “cleanup” functions to execute at program termination time. Chapter 15, “Concurrency: Threads and Processes” Covers Python’s functionality for concurrent execution, both via multiple threads running within one process and via multiple processes running on a single machine.1 This chapter also covers how to access the process’s environ‐ ment, and how to access files via memory-mapping mechanisms. Chapter 16, “Numeric Processing” Covers Python’s features for numeric computations, both in standard library modules and in third-party extension packages; in particular, how to use deci‐ mal numbers or fractions instead of the default binary floating-point numbers. This chapter also covers how to get and use pseudorandom and truly random numbers, and how to speedily process whole arrays (and matrices) of numbers. Chapter 17, “Testing, Debugging, and Optimizing” Covers Python tools and approaches that help you make sure that your pro‐ grams are correct (i.e., that they do what they’re meant to do), find and fix errors in your programs, and check and enhance your programs’ performance. This chapter also covers the concept of warnings and the Python library mod‐ ule that deals with them. Preface | xi
📄 Page 14
Part IV, Network and Web Programming Chapter 18, “Networking Basics” Covers the basics of networking with Python. Chapter 19, “Client-Side Network Protocol Modules” Covers modules in Python’s standard library to write network client programs, particularly for dealing with various network protocols from the client side, sending and receiving emails, and handling URLs. Chapter 20, “Serving HTTP” Covers how to serve HTTP for web applications in Python, using popular third-party lightweight Python frameworks leveraging Python’s WSGI standard interface to web servers. Chapter 21, “Email, MIME, and Other Network Encodings” Covers how to process email messages and other network-structured and enco‐ ded documents in Python. Chapter 22, “Structured Text: HTML” Covers popular third-party Python extension modules to process, modify, and generate HTML documents. Chapter 23, “Structured Text: XML” Covers Python library modules and popular extensions to process, modify, and generate XML documents. Part V, Extending, Distributing, and Version Upgrade and Migration Chapters 24 and 25 are included in summary form in the print edition of this book. You will find the full content of these chapters in the supporting online repository, described in “How to Contact Us” on page xv. Chapter 24, “Packaging Programs and Extensions” Covers tools and modules to package and share Python modules and applica‐ tions. Chapter 25, “Extending and Embedding Classic Python” Covers how to code Python extension modules using Python’s C API, Cython, and other tools. Chapter 26, “v3.7 to v3.n Migration” Covers topics and best practices for planning and deploying version upgrades for Python users ranging from individuals to library maintainers to enterprise- wide deployment and support staff. Appendix, “New Features and Changes in Python 3.7 Through 3.11” Provides a detailed list of features and changes in Python language syntax and the standard library, by version. xii | Preface
📄 Page 15
2 For example, to accommodate the widespread changes in Python 3.9 and 3.10 in type annota‐ tions, most of Chapter 5 uses Python 3.10 as the base version for features and examples. Conventions Used in This Book The following conventions are used throughout this book. Reference Conventions In the function/method reference entries, when feasible, each optional parameter is shown with a default value using the Python syntax name=value. Built-in functions need not accept named parameters, so parameter names may not be significant. Some optional parameters are best explained in terms of their presence or absence, rather than through default values. In such cases, we indicate that a parameter is optional by enclosing it in brackets ([]). When more than one argument is optional, brackets can be nested. Version Conventions This book covers changes and features in Python versions 3.7 through 3.11. Python 3.7 serves as the base version for all tables and code examples, unless otherwise noted.2 You will see these notations to indicate changes or features added and removed across the range of covered versions: • 3.x+ marks a feature introduced in version 3.x, not available in prior versions. • -3.x marks a feature removed in version 3.x, available only in prior versions. Typographic Conventions Please note that, for display reasons, our code snippets and samples may sometimes depart from PEP 8. We do not recommend taking such liberties in your code. Instead, use a utility like black to adopt a canonical layout style. The following typographical conventions are used in this book: Italic Used for file and directory names, program names, URLs, and to introduce new terms. Constant width Used for command-line output and code examples, as well as for code elements that appear in the text, including methods, functions, classes, and modules. Constant width italic Used to show text to be replaced with user-supplied values in code examples and commands. Preface | xiii
📄 Page 16
Constant width bold Used for commands to be typed at a system command line and to indicate code output in Python interpreter session examples. Also used for Python keywords. This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. Using Code Examples This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant por‐ tion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Python in a Nutshell, 4th ed., by Alex Martelli, Anna Martelli Ravenscroft, Steve Holden, and Paul McGuire. Copyright 2023, 978-1-098-11355-1.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. xiv | Preface
📄 Page 17
O’Reilly Online Learning For more than 40 years, O’Reilly Media has pro‐ vided technology and business training, knowl‐ edge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) The book has its own GitHub repository, where we list errata, examples, and any additional information. The repository also contains the full content of Chapters 24 and 25, for which there was insufficient space in the printed volume. You will find it at https://github.com/pynutshell/pynut4. We have tested and verified the information in this book to the best of our ability, but you may find that features have changed (or even that we have made mistakes!). Please let the publisher know about any errors you find, as well as your suggestions for future editions. O’Reilly has a web page for this book, where they list errata, examples, and any addi‐ tional information. You can access this page at https://oreil.ly/python-nutshell-4e. To comment or ask technical questions about this book, send email to pynut4@gmail.com. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media. Follow us on Twitter: https://twitter.com/oreillymedia. Watch us on YouTube: https://www.youtube.com/oreillymedia. Preface | xv
📄 Page 18
3 Nor would it have so many footnotes! Acknowledgments Many thanks to O’Reilly editors and staff Amanda Quinn, Brian Guerin, Zan McQuade, and Kristen Brown. Special thanks to our editor, Angela Rufino, who did the heavy lifting to keep us on track to get this book completed on time! Also, thanks to our excellent copyeditor Rachel Head for helping us to seem more erudite than we are, and to our production editor, Christopher Faucher, for helping ensure the book looked its best in both printed and electronic formats. Thanks to our hardworking tech reviewers, David Mertz, Mark Summerfield, and Pankaj Gaijar, who read through every explanation and example in the book’s draft. Without them, this book would not have been as accurate.3 All errors that remain are entirely our own. Thanks also to Luciano Ramalho, the whole PyPy team, Sebastián Ramírez, Fabio Pliger, Miguel Grinberg, and the Python Packaging Authority team for their help on selected portions of the book, and to Google for its useful Workspace online collaboration tools, without which our intense communication (and coordination among authors on different continents!) would have been far less easy and efficient. Last but by no means least, the authors and all readers of this book owe a huge debt of thanks to the core developers of the Python language itself, without whose heroic efforts there would be no need for this book. xvi | Preface
📄 Page 19
1 For Android, see https://wiki.python.org/moin/Android, and for iPhone and iPad, see Python for iOS and iPadOS. 1 Introduction to Python Python is a well-established general-purpose programming language, first released by its creator, Guido van Rossum, in 1991. This stable and mature language is high-level, dynamic, object-oriented, and cross-platform—all very attractive char‐ acteristics. Python runs on macOS, most current Unix variants including Linux, Windows, and, with some tweaks, mobile platforms.1 Python offers high productivity for all phases of the software life cycle: analysis, design, prototyping, coding, testing, debugging, tuning, documentation, and, of course, maintenance. The language’s popularity has seen steadily increasing growth for many years, becoming the TIOBE index leader in October 2021. Today, familiar‐ ity with Python is a plus for every programmer: it has snuck into most niches, with useful roles to play in any software solution. Python provides a unique mix of elegance, simplicity, practicality, and sheer power. You’ll quickly become productive with Python, thanks to its consistency and regu‐ larity, its rich standard library, and the many third-party packages and tools that are readily available for it. Python is easy to learn, so it is quite suitable if you are new to programming, yet is also powerful enough for the most sophisticated expert. The Python Language The Python language, while not minimalist, is spare, for good pragmatic reasons. Once a language offers one good way to express a design, adding other ways has, at best, modest benefits; the cost of language complexity, though, grows more than linearly with the number of features. A complicated language is harder to learn and 1
📄 Page 20
master (and to implement efficiently and without bugs) than a simpler one. Com‐ plications and quirks in a language hamper productivity in software development, particularly in large projects, where many developers cooperate and, often, maintain code originally written by others. Python is fairly simple, but not simplistic. It adheres to the idea that, if a language behaves a certain way in some contexts, it should ideally work similarly in all contexts. Python follows the principle that a language should not have “convenient” shortcuts, special cases, ad hoc exceptions, overly subtle distinctions, or mysterious and tricky under-the-covers optimizations. A good language, like any other well- designed artifact, must balance general principles with taste, common sense, and a lot of practicality. Python is a general-purpose programming language: its traits are useful in almost any area of software development. There is no area where Python cannot be part of a solution. “Part” is important here; while many developers find that Python fills all of their needs, it does not have to stand alone. Python programs can cooperate with a variety of other software components, making it the right language for gluing together components in other languages. A design goal of the language is, and has long been, to “play well with others.” Python is a very high-level language (VHLL). This means that it uses a higher level of abstraction, conceptually further away from the underlying machine, than classic compiled languages such as C, C++, and Rust, traditionally called “high-level languages.” Python is simpler, faster to process (both for humans and for tools), and more regular than classic high-level languages. This affords high programmer productivity, making Python a strong development tool. Good compilers for classic compiled languages can generate binary code that runs faster than Python. In most cases, however, the performance of Python-coded applications is sufficient. When it isn’t, apply the optimization techniques covered in “Optimization” on page 541 to improve your program’s performance while keeping the benefit of high productivity. In terms of language level, Python is comparable to other powerful VHLLs like JavaScript, Ruby, and Perl. The advantages of simplicity and regularity, however, remain on Python’s side. Python is an object-oriented programming language, but it lets you program in both object-oriented and procedural styles, with a touch of functional programming too, mixing and matching as your application requires. Python’s object-oriented features are conceptually similar to those of C++ but simpler to use. The Python Standard Library and Extension Modules There is more to Python programming than just the language: the standard library and other extension modules are almost as important for Python use as the lan‐ guage itself. The Python standard library supplies many well-designed, solid Python modules for convenient reuse. It includes modules for such tasks as representing data, processing text, interacting with the operating system and filesystem, and web programming, and works on all platforms supported by Python. 2 | Chapter 1: Introduction to Python
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List