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 now! 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
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Modern Python Cookbook

You're reading from   Modern Python Cookbook 130+ updated recipes for modern Python 3.12 with new techniques and tools

Arrow left icon
Product type Paperback
Published in Jul 2024
Publisher Packt
ISBN-13 9781835466384
Length 818 pages
Edition 3rd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Steven F. Lott Steven F. Lott
Author Profile Icon Steven F. Lott
Steven F. Lott
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Chapter 1 Numbers, Strings, and Tuples FREE CHAPTER 2. Chapter 2 Statements and Syntax 3. Chapter 3 Function Definitions 4. Chapter 4 Built-In Data Structures Part 1: Lists and Sets 5. Chapter 5 Built-In Data Structures Part 2: Dictionaries 6. Chapter 6 User Inputs and Outputs 7. Chapter 7 Basics of Classes and Objects 8. Chapter 8 More Advanced Class Design 9. Chapter 9 Functional Programming Features 10. Chapter 10 Working with Type Matching and Annotations 11. Chapter 11 Input/Output, Physical Format, and Logical Layout 12. Chapter 12 Graphics and Visualization with Jupyter Lab 13. Chapter 13 Application Integration: Configuration 14. Chapter 14 Application Integration: Combination 15. Chapter 15 Testing 16. Chapter 16 Dependencies and Virtual Environments 17. Chapter 17 Documentation and Style 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

You have been reading a chapter from
Modern Python Cookbook - Third Edition
Published in: Jul 2024
Publisher: Packt
ISBN-13: 9781835466384
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime