Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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

Arrow left icon
Profile Icon Steven F. Lott
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9 (21 Ratings)
Paperback Jul 2024 818 pages 3rd Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Steven F. Lott
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9 (21 Ratings)
Paperback Jul 2024 818 pages 3rd Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781835466384
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

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

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
(21 Ratings)
5 star 85.7%
4 star 14.3%
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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.