Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Modern Python Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
Modern Python Cookbook

Modern Python Cookbook - Third Edition

By : Steven F. Lott
4.9 (17)
close
close
Modern Python Cookbook

Modern Python Cookbook

4.9 (17)
By: Steven F. Lott

Overview of this book

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.
Table of Contents (20 chapters)
close
close
18
Other Books You May Enjoy
19
Index

1.10 Using NamedTuples to simplify item access in tuples

When we worked with tuples, we had to remember the positions as numbers. When we use a (r,g,b) tuple to represent a color, can we use ”red” instead of zero, ”green” instead of 1, and ”blue” instead of 2?

1.10.1 Getting ready

Let’s continue looking at items in recipes. The regular expression for parsing the string had three attributes: ingredient, amount, and unit. We used the following pattern with names for the various substrings:

r’(?P<ingredient>\w+):\s+(?P<amount>\d+)\s+(?P<unit>\w+)’)

The resulting data tuple looked like this:

>>> item = match.groups() 
 
>>> item 
 
(’Kumquat’, ’2’, ’cups’)

While the matching between ingredient, amount, and unit is pretty clear, using something like the following isn’t ideal. What does 1 mean? Is it really the quantity?

>>> from fractions import Fraction 
 
>>> Fraction(item[1]) 
 
Fraction(2, 1)

We want to define tuples with names, as well as positions.

1.10.2 How to do it...

  1. We’ll use the NamedTuple class definition from the typing package:

    >>> from typing import NamedTuple
  2. With this base class definition, we can define our own unique tuples, with names for the items:

    >>> class Ingredient(NamedTuple): 
     
    ...     ingredient: str 
     
    ...     amount: str 
     
    ...     unit: str
  3. Now, we can create an instance of this unique kind of tuple by using the classname:

    >>> item_2 = Ingredient(’Kumquat’, ’2’, ’cups’)
  4. When we want a value from the tuple, we can use a name instead of the position:

    >>> Fraction(item_2.amount) 
     
    Fraction(2, 1) 
     
    >>> f"Use {item_2.amount} {item_2.unit} fresh {item_2.ingredient}" 
     
    ’Use 2 cups fresh Kumquat’

1.10.3 How it works...

The NamedTuple class definition introduces a core concept from Chapter 7. We’ve extended the base class definition to add unique features for our application. In this case, we’ve named the three attributes each Ingredient tuple must contain.

Because a subclass of NamedTuple class is a tuple, the order of the attribute names is fixed. We can use a reference like the expression item_2[0] as well as the expression item_2.ingredient. Both names refer to the item in index 0 of the tuple, item_2.

The core tuple types can be called ”anonymous tuples” or maybe ”index-only tuples.” This can help to distinguish them from the more sophisticated ”named tuples” introduced through the typing module.

Tuples are very useful as tiny containers of closely related data. Using the NamedTuple class definition makes them even easier to work with.

1.10.4 There’s more...

We can have a mixed collection of values in a tuple or a named tuple. We need to perform conversion before we can build the tuple. It’s important to remember that a tuple cannot ever be changed. It’s an immutable object, similar in many ways to the way strings and numbers are immutable.

For example, we might want to work with amounts that are exact fractions. Here’s a more sophisticated definition:

>>> from typing import NamedTuple 
 
>>> from fractions import Fraction 
 
>>> class IngredientF(NamedTuple): 
 
...     ingredient: str 
 
...     amount: Fraction 
 
...     unit: str

These objects require some care to create. If we’re using a bunch of strings, we can’t simply build this object from three string values; we need to convert the amount into a Fraction instance. Here’s an example of creating an item using a Fraction conversion:

>>> item_3 = IngredientF(’Kumquat’, Fraction(’2’), ’cups’)

This tuple has a more useful value for the amount of each ingredient. We can now do mathematical operations on the amounts:

>>> f’{item_3.ingredient} doubled: {item_3.amount * 2}’ 
 
’Kumquat doubled: 4’

It’s very handy to explicitly state the data type within the NamedTuple class definition. It turns out Python doesn’t use the type information directly. Other tools, for example, mypy, can check the type hints in a NamedTuple against the operations in the rest of the code to be sure they agree.

1.10.5 See also

  • We’ll look at class definitions in Chapter 7.

Join our community Discord space

Join our Python Discord workspace to discuss and find out more about the book: https://packt.link/dHrHU

PIC

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Modern Python Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon