Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Modern Python Cookbook
Modern Python Cookbook

Modern Python Cookbook: 130+ updated recipes for modern Python 3.12 with new techniques and tools , Third Edition

eBook
$9.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Modern Python Cookbook

2
Statements and Syntax

Python syntax is designed to be simple. In this chapter, we’ll look at some of the most commonly used statements in the language as a way to understand the rules. Concrete examples can help clarify the language’s syntax.

We’ll cover some of the basics of creating script files first. Then we’ll move on to looking at some of the more commonly used statements. Python only has about 20 or so different kinds of imperative statements in the language. We’ve already looked at two kinds of statements in Chapter 1, the assignment statement and the expression statement.

When we write something like this:

>>> print("hello world") 
 
hello world

We’re actually executing a statement that contains only the evaluation of a function, print(). This kind of statement—where we evaluate a function or a method of an object—is common.

The other kind of statement we&...

2.1 Writing Python script and module files – syntax basics

The point of Python (and programming in general) is to create automated solutions to problems that involve data and processing. Further, the software we write is a kind of knowledge representation; this means clarity is perhaps the most important quality aspect of software.

In Python, we implement automated solutions by creating script files. These are the top-level, main programs of Python programming. In addition to main scripts, we may also create modules (and packages of modules) to help organize the software into intellectually manageable chunks. A script is a module; however, it has a distinct intent to do useful processing when started by the OS.

A key part of creating clear, readable Python files is making sure our code follows the widely adopted conventions.

For example, we need to be sure to save our files in UTF-8 encoding. While ASCII encoding is still supported by Python,...

2.2 Writing long lines of code

There are many times when we need to write lines of code that are so long that they’re very hard to read. Many people like to limit the length of a line of code to 80 characters or fewer. It’s a well-known principle of graphic design that a narrower area of text is easier to read. See http://webtypography.net/2.1.2 for a deeper discussion of line width and readability.

While fewer characters per line is easier on the eyes, our code can refuse to cooperate with this principle. How can we break long Python statements into more manageable pieces?

2.2.1 Getting ready

Let’s say we’ve got something like this:

>>> import math
>>> example_value = (63/25) * (17+15*math.sqrt(5)) / (7+15*math.sqrt(5))
>>> mantissa_fraction, exponent = math.frexp(example_value)
>>> mantissa_whole = int(mantissa_fraction*2**53)
>>> message_text = f’...

2.3 Including descriptions and documentation

When we have a useful script, we often need to leave notes for ourselves—and others—on what it does, how it solves some particular problem, and when it should be used. This recipe contains a suggested outline to help make the documentation reasonably complete.

2.3.1 Getting ready

If we’ve used the Writing Python script and module files – syntax basics recipe to start a script file, we’ll have a small documentation string in place. We’ll expand on this documentation string in this recipe.

There are other places where documentation strings should be used. We’ll look at these additional locations in Chapter 3 and Chapter 7.

We have two general kinds of modules for which we’ll be writing summary docstrings:

  • Library modules: These files will contain mostly function definitions as well as class definitions...

2.4 Writing better docstrings with RST markup

When we have a useful script, we often need to leave notes on what it does, how it works, and when it should be used. Many tools for producing documentation, including Docutils, work with RST markup. This allows us to write plain text documentation. It can include some special punctuation to pick a bold or italic font variant to call attention to details. In addition, RST permits organizing content via lists and section headings.

2.4.1 Getting ready

In the Including descriptions and documentation recipe, we looked at putting some basic documentation into a module. We’ll look at a few of the RST formatting rules for creating readable documentation.

2.4.2 How to do it...

  1. Start with an outline of the key point, creating RST section titles to organize the material. A section title has a one-line title followed by a line of underline characters...

2.5 Designing complex if...elif chains

In most cases, our scripts will involve a number of choices. Sometimes the choices are simple, and we can judge the quality of the design with a glance at the code. In other cases, the choices are more complicated, and it’s not easy to determine whether or not our if statements are designed properly to handle all of the conditions.

In the simplest case, we have one condition, C, and its inverse, ¬C. These are the two conditions for an if...else statement. One condition, C, is stated in the if clause; the inversion condition, ¬C, is implied in the else clause.

This follows the Law of the Excluded Middle: we’re claiming there’s no missing alternative between the two conditions, C and ¬C. For a complex condition, though, this can be difficult to visualize.

If we have something like:


 
 
if weather == Weather.RAIN and plan == Plan.GO_OUT: 
 
    ...

2.6 Saving intermediate results with the := ”walrus” operator

Sometimes we’ll have a complex condition where we want to preserve an expensive intermediate result for later use. Imagine a condition that involves a complex calculation; the cost of computing is high measured in time, input-output operations, memory resources, or all three.

An example includes doing repetitive searches using the Regular Expression (re) package. A match() method can do quite a bit of computation before returning either a Match object or a None object to show the pattern wasn’t found. Once this computation is completed, we may have several uses for the result, and we emphatically do not want to perform the computation again. Often, the initial use is the simple check to see if the result is a Match object or None.

This is an example where it can be helpful to assign a name to the value of an expression and also use the expression in an if statement. We...

2.7 Avoiding a potential problem with break statements

The common way to understand a for statement is that it creates a for all condition. At the end of the statement, we can assert that, for all items in a collection, the processing in the body of the statement has been done.

This isn’t the only meaning a for statement can have. When the break statement is used inside the body of a for statement, it changes the semantics to there exists. When the break statement leaves the for (or while) statement, we can assert there exists at least one item that caused the enclosing statement to end.

There’s a side issue here. What if the for statement ends without executing the break statement? Either way, we’re at the statement after the for statement. The condition that’s true upon leaving a for or while statement with a break statement can be ambiguous. We can’t easily tell; this recipe gives some design guidance.

The problem...

2.8 Leveraging exception matching rules

The try statement lets us capture an exception. When an exception is raised, we have a number of choices for handling it:

  • Ignore it: If we do nothing, the program stops. We can do this in two ways—don’t use a try statement in the first place, or don’t have a matching except clause in the try statement.

  • Log it: We can write a message and use a raise statement to let the exception propagate after writing to a log. The expectation is that this will stop the program.

  • Recover from it: We can write an except clause to do some recovery action to undo any effects of the partially completed try clause.

  • Silence it: If we do nothing (that is, use the pass statement), then processing is resumed after the try statement. This silences the exception, but does not correct the underlying problem, or supply alternative results as a recovery attempt.

  • Rewrite it: We can raise a different...

2.9 Avoiding a potential problem with an except: clause

There are some common mistakes in exception handling. These can cause programs to become unresponsive.

One of the mistakes we can make is to use the except: clause with no named exception class to match. There are a few other mistakes that we can make if we’re not cautious about the exceptions we try to handle.

This recipe will show some common exception handling errors that we can avoid.

2.9.1 Getting ready

When code can raise a variety of exceptions, it’s sometimes tempting to try and match as many as possible. Matching too many exception classes can interfere with stopping a misbehaving Python program. We’ll extend the idea of what not to do in this recipe.

2.9.2 How to do it...

We need to avoid using the bare except: clause. Instead, use except Exception: to match the most general kind of exception that an application...

2.10 Concealing an exception root cause

Exceptions contain a root cause. The default behavior of internally raised exceptions is to use an implicit __context__ attribute to include the root cause of an exception. In some cases, we may want to deemphasize the root cause because it’s misleading or unhelpful for debugging.

This technique is almost always paired with an application or library that defines a unique exception. The idea is to show the unique exception without the clutter of an irrelevant exception from outside the application or library.

2.10.1 Getting ready

Assume we’re writing some complex string processing. We’d like to treat a number of different kinds of detailed exceptions as a single generic error so that users of our software are insulated from the implementation details. We can attach details to the generic error.

2.10.2 How to do it...

  1. To create...

2.11 Managing a context using the with statement

There are many instances where our scripts will be entangled with external resources. The most common examples are disk files and network connections to external hosts. A common bug is retaining these entanglements forever, tying up these resources uselessly. These are sometimes called a memory leak because the available memory is reduced each time a new file is opened without closing a previously used file.

We’d like to isolate each entanglement so that we can be sure that the resource is acquired and released properly. The idea is to create a context in which our script uses an external resource. At the end of the context, our program is no longer bound to the resource and we want to be guaranteed that the resource is released.

2.11.1 Getting ready

Let’s say we want to write lines of data to a file in CSV format. When we’re done, we want to be sure that the file is closed...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • New chapters on type matching, data visualization, dependency management, and more
  • Comprehensive coverage of Python 3.12 with updated recipes and techniques
  • Provides practical examples and detailed explanations to solve real-world problems efficiently

Description

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.

Who is this book 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

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

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 31, 2024
Length: 818 pages
Edition : 3rd
Language : English
ISBN-13 : 9781835460757
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 31, 2024
Length: 818 pages
Edition : 3rd
Language : English
ISBN-13 : 9781835460757
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 140.97
Mastering Python Design Patterns
$39.99
Python Real-World Projects
$45.99
Modern Python Cookbook
$54.99
Total $ 140.97 Stars icon
Banner background image

Table of Contents

19 Chapters
Chapter 1 Numbers, Strings, and Tuples Chevron down icon Chevron up icon
Chapter 2 Statements and Syntax Chevron down icon Chevron up icon
Chapter 3 Function Definitions Chevron down icon Chevron up icon
Chapter 4 Built-In Data Structures Part 1: Lists and Sets Chevron down icon Chevron up icon
Chapter 5 Built-In Data Structures Part 2: Dictionaries Chevron down icon Chevron up icon
Chapter 6 User Inputs and Outputs Chevron down icon Chevron up icon
Chapter 7 Basics of Classes and Objects Chevron down icon Chevron up icon
Chapter 8 More Advanced Class Design Chevron down icon Chevron up icon
Chapter 9 Functional Programming Features Chevron down icon Chevron up icon
Chapter 10 Working with Type Matching and Annotations Chevron down icon Chevron up icon
Chapter 11 Input/Output, Physical Format, and Logical Layout Chevron down icon Chevron up icon
Chapter 12 Graphics and Visualization with Jupyter Lab Chevron down icon Chevron up icon
Chapter 13 Application Integration: Configuration Chevron down icon Chevron up icon
Chapter 14 Application Integration: Combination Chevron down icon Chevron up icon
Chapter 15 Testing Chevron down icon Chevron up icon
Chapter 16 Dependencies and Virtual Environments Chevron down icon Chevron up icon
Chapter 17 Documentation and Style Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9
(18 Ratings)
5 star 88.9%
4 star 11.1%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




N/A Nov 05, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Samuel de Zoete Oct 01, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
There are many good books to learn how to code in Python. However, most books and courses show you how it's done and move on to the next topic. This book is different. It not only shows you how it's done, it will explain why it's done this way and how it works. This additional inside is going to make a difference in you being an average programmer or being a really good one!
Amazon Verified review Amazon
Stephan Miller Aug 03, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Many coding books lose much of their usefulness after you learn the concepts they have to teach you. But recipe books are great because they become permanent references. When you want to do something specific, you can go right to it. Sometimes I just browse them to see if there is any code that triggers an idea or to run into something I never thought of doing. And this book has more than 130 recipes in my favorite programming language.
Amazon Verified review Amazon
Robert Aug 04, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The review covers the third edition of Modern Python Cookbook. This book is not necessarily for the first-time Python user, but if you have some previous experience, this book is the one you want in your collection. It starts with simple Python lessons about numbers, strings, and tuples then progresses into functions, lists, dictionaries, and how to create classes. The chapter about graphics and visualization using the Jupyter notebook was a nice touch. The book is easy to follow and the examples are extremely helpful. I highly recommend this book.
Amazon Verified review Amazon
Paul Gerber Aug 05, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've recently finished reading "Modern Python Cookbook 3rd Edition" by Steve Lott, and I must say it was an absolutely delightful read. This book is packed with practical recipes and examples that cater to both intermediate and advanced Python developers.One of the standout features of this book is its clear and concise explanations, which made it easy to grasp even the more complex concepts.Another highlight was the section on testing and debugging. The recipes on using pytest and mocking were extremely useful.Steve Lott's emphasis on writing clean and maintainable code resonated with me deeply. His approach to leveraging Python's powerful features like decorators, context managers, and metaclasses has not only improved the quality of my code but also boosted my productivity.Overall, "Modern Python Cookbook 3rd Edition" is a treasure trove of Python wisdom. Whether you're looking to refine your skills or seeking new techniques to tackle challenging problems, this book is an invaluable resource. Highly recommended for anyone serious about mastering Python!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.