Modern Python Cookbook: 130+ updated recipes for modern Python 3.12 with new techniques and tools. 3 Ed

Modern Python Cookbook: 130+ updated recipes for modern Python 3.12 with new techniques and tools. 3 Ed

Modern Python Cookbook: 130+ updated recipes for modern Python 3.12 with new techniques and tools. 3 Ed
Автор: Lott Steven F.
Дата выхода: 2024
Издательство: Packt Publishing Limited
Количество страниц: 819
Размер файла: 2.6 MB
Тип файла: PDF
Добавил: codelibs
 Проверить на вирусы  Дополнительные материалы 

Cover....1

Copyright....3

Contributors....4

Table of Contents....8

Preface....16

Chapter 1: Numbers, Strings, and Tuples....24

Choosing between float, decimal, and fraction....25

Choosing between true division and floor division....32

String parsing with regular expressions....36

Building complicated strings with f-strings....41

Building complicated strings from lists of strings....46

Using the Unicode characters that aren't on our keyboards....49

Encoding strings – creating ASCII and UTF-8 bytes....52

Decoding bytes – how to get proper characters from some bytes....56

Using tuples of items....59

Using NamedTuples to simplify item access in tuples....63

Chapter 2: Statements and Syntax....68

Writing Python script and module files – syntax basics....70

Writing long lines of code....75

Including descriptions and documentation....80

Writing better docstrings with RST markup....85

Designing complex if...elif chains....90

Saving intermediate results with the := "walrus" operator....96

Avoiding a potential problem with break statements....100

Leveraging exception matching rules....104

Avoiding a potential problem with an except: clause....109

Concealing an exception root cause....111

Managing a context using the with statement....114

Chapter 3: Function Definitions....120

Function parameters and type hints....121

Designing functions with optional parameters....126

Using super flexible keyword parameters....132

Forcing keyword-only arguments with the * separator....137

Defining position-only parameters with the / separator....142

Picking an order for parameters based on partial functions....145

Writing clear documentation strings with RST markup....152

Designing recursive functions around Python's stack limits....157

Writing testable scripts with the script-library switch....162

Chapter 4: Built-In Data Structures Part 1: Lists and Sets....168

Choosing a data structure....169

Building lists – literals, appending, and comprehensions....174

Slicing and dicing a list....180

Shrinking lists – deleting, removing, and popping....186

Writing list-related type hints....192

Reversing a copy of a list....196

Building sets – literals, adding, comprehensions, and operators....200

Shrinking sets – remove(), pop(), and difference....207

Writing set-related type hints....211

Chapter 5: Built-In Data Structures Part 2: Dictionaries....218

Creating dictionaries – inserting and updating....219

Shrinking dictionaries – the pop() method and the del statement....225

Writing dictionary-related type hints....228

Understanding variables, references, and assignment....234

Making shallow and deep copies of objects....238

Avoiding mutable default values for function parameters....244

Chapter 6: User Inputs and Outputs....252

Using the features of the print() function....253

Using input() and getpass() for user input....258

Debugging with f"{value=}" strings....264

Using argparse to get command-line input....266

Using invoke to get command-line input....272

Using cmd to create command-line applications....276

Using the OS environment settings....280

Chapter 7: Basics of Classes and Objects....286

Using a class to encapsulate data and processing....288

Essential type hints for class definitions....292

Designing classes with lots of processing....297

Using typing.NamedTuple for immutable objects....303

Using dataclasses for mutable objects....306

Using frozen dataclasses for immutable objects....312

Optimizing small objects with __slots__....315

Using more sophisticated collections....320

Extending a built-in collection – a list that does statistics....326

Using properties for lazy attributes....330

Creating contexts and context managers....336

Managing multiple contexts with multiple resources....342

Chapter 8: More Advanced Class Design....350

Choosing between inheritance and composition – the "is-a" question....351

Separating concerns via multiple inheritance....358

Leveraging Python's duck typing....365

Managing global and singleton objects....370

Using more complex structures – maps of lists....376

Creating a class that has orderable objects....381

Deleting from a list of complicated objects....387

Chapter 9: Functional Programming Features....394

Writing generator functions with the yield statement....396

Applying transformations to a collection....404

Using stacked generator expressions....409

Picking a subset – three ways to filter....417

Summarizing a collection – how to reduce....422

Combining the map and reduce transformations....428

Implementing ``there exists'' processing....435

Creating a partial function....440

Writing recursive generator functions with the yield from statement....446

Chapter 10: Working with Type Matching and Annotations....454

Designing with type hints....455

Using the built-in type matching functions....463

Using the match statement....467

Handling type conversions....471

Implementing more strict type checks with Pydantic....478

Including run-time valid value checks....485

Chapter 11: Input/Output, Physical Format, and Logical Layout....494

Using pathlib to work with filenames....497

Replacing a file while preserving the previous version....505

Reading delimited files with the CSV module....511

Using dataclasses to simplify working with CSV files....518

Reading complex formats using regular expressions....523

Reading JSON and YAML documents....531

Reading XML documents....539

Reading HTML documents....546

Chapter 12: Graphics and Visualization with Jupyter Lab....556

Starting a Notebook and creating cells with Python code....558

Ingesting data into a notebook....563

Using pyplot to create a scatter plot....569

Using axes directly to create a scatter plot....575

Adding details to markdown cells....581

Including Unit Test Cases in a Notebook....585

Chapter 13: Application Integration: Configuration....590

Finding configuration files....592

Using TOML for configuration files....598

Using Python for configuration files....603

Using a class as a namespace for configuration....608

Designing scripts for composition....614

Using logging for control and audit output....619

Chapter 14: Application Integration: Combination....628

Combining two applications into one....629

Combining many applications using the Command design pattern....637

Managing arguments and configuration in composite applications....643

Wrapping and combining CLI applications....650

Wrapping a program and checking the output....655

Chapter 15: Testing....664

Using docstrings for testing....666

Testing functions that raise exceptions....674

Handling common doctest issues....677

Unit testing with the unittest module....684

Combining unittest and doctest tests....690

Unit testing with the pytest module....695

Combining pytest and doctest tests....700

Testing things that involve dates or times....704

Testing things that involve randomness....709

Mocking external resources....716

Chapter 16: Dependencies and Virtual Environments....726

Creating environments using the built-in venv....729

Installing packages with a requirements.txt file....734

Creating a pyproject.toml file....739

Using pip-tools to manage the requirements.txt file....746

Using Anaconda and the conda tool....750

Using the poetry tool....755

Coping with changes in dependencies....759

Chapter 17: Documentation and Style....766

The bare minimum: a README.rst file....767

Installing Sphinx and creating documentation....772

Using Sphinx autodoc to create the API reference....777

Identifying other CI/CD tools in pyproject.toml....783

Using tox to run comprehensive quality checks....787

Other Books You May Enjoy....796

Packt Page....794

Index....800

Blank Page....819

Python is the go-to language for developers, engineers, data scientists, and hobbyists worldwide. Known for its versatility, Python can efficiently power applications, offering remarkable speed, safety, and scalability. This book distills Python into a collection of straightforward recipes, providing insights into specific language features within various contexts, making it an indispensable resource for mastering Python and using it to handle real-world use cases.

The third edition of Modern Python Cookbook provides an in-depth look into Python 3.12, offering more than 140 new and updated recipes that cater to both beginners and experienced developers. This edition introduces new chapters on documentation and style, data visualization with Matplotlib and Pyplot, and advanced dependency management techniques using tools like Poetry and Anaconda. With practical examples and detailed explanations, this cookbook helps developers solve real-world problems, optimize their code, and get up to date with the latest Python features.

What you will learn

  • Master core Python data structures, algorithms, and design patterns
  • Implement object-oriented designs and functional programming features
  • Use type matching and annotations to make more expressive programs
  • Create useful data visualizations with Matplotlib and Pyplot
  • Manage project dependencies and virtual environments effectively
  • Follow best practices for code style and testing
  • Create clear and trustworthy documentation for your projects

Who this book is for

This Python book is for web developers, programmers, enterprise programmers, engineers, and big data scientists. If you are a beginner, this book offers helpful details and design patterns for learning Python. If you are experienced, it will expand your knowledge base. Fundamental knowledge of Python programming and basic programming principles will be helpful


Похожее:

Список отзывов:

Нет отзывов к книге.