What is "named tuple" in Python?

Keywords: Python Attribute

read In Python 3.1 Of After change , I found some accidents

The sys.version \ u info tuple is now a named tuple:

I've never heard of named tuples before, and I think elements can be indexed by numbers (for example, in tuples and lists) or by keys (for example, in dictionaries). I never thought they could be indexed at the same time.

So my question is:

  • What is tuple?
  • How to use them?
  • Why / when should named tuples be used instead of normal tuples?
  • Why / when should normal tuples be used instead of named tuples?
  • Is there a "named list" (a variable version of a named tuple)?

#1st floor

namedtuple Is a factory function used to create a tuple class. With this class, we can create tuples that can be called by name.

import collections

#Create a namedtuple class with names "a" "b" "c"
Row = collections.namedtuple("Row", ["a", "b", "c"], verbose=False, rename=False)   

row = Row(a=1,b=2,c=3) #Make a namedtuple from the Row class we created

print row    #Prints: Row(a=1, b=2, c=3)
print row.a  #Prints: 1
print row[0] #Prints: 1

row = Row._make([2, 3, 4]) #Make a namedtuple from a list of values

print row   #Prints: Row(a=2, b=3, c=4)

#2nd floor

Inside Python, there is a very useful container called named tuples, which can be used to create the definition of a class and has all the functions of the original tuples.

Using named tuples will be directly applied to the default class template to generate a simple class. This method allows a lot of code to improve readability, and is very convenient when defining classes.

#3rd floor

Named tuples allow backward compatibility checking of such versions of code

>>> sys.version_info[0:2]
(3, 1)

At the same time, it makes the future code clearer by using this syntax

>>> sys.version_info.major
3
>>> sys.version_info.minor
1

#4th floor

Named tuples are basically lightweight object types that are easy to create. Named tuple instances can be referenced using class object variable dereference or standard tuple syntax. Except that they are immutable, they can be used similarly for struct or other common record types. They are added in Python 2.6 and Python 3.0, although In Python 2.4 Yes Realization Of secret .

For example, points are usually represented as tuples (x, y). This results in the following code:

pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)

from math import sqrt
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)

With named tuples, it becomes more readable:

from collections import namedtuple
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)

from math import sqrt
line_length = sqrt((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)

However, named tuples are still backward compatible with normal tuples, so the following is still valid:

Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)

from math import sqrt
# use index referencing
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
 # use tuple unpacking
x1, y1 = pt1

Therefore, wherever you think object notation will make your code more pythonic and easier to read, you should use named tuples instead of tuples. I've personally started using them to represent very simple value types, especially when passing them as arguments to functions. It makes the function more readable without seeing the context of the tuple wrapper.

In addition, you can replace ordinary immutable classes that have no functionality, just replace them with fields. You can even use named tuple types as base classes:

class Point(namedtuple('Point', 'x y')):
    [...]

However, like tuples, attributes in named tuples are immutable:

>>> Point = namedtuple('Point', 'x y')
>>> pt1 = Point(1.0, 5.0)
>>> pt1.x = 2.0
AttributeError: can't set attribute

If you want to be able to change values, you need another type. about Variable record type , there is a convenient usage , which allows you to set a new value for the property.

>>> from rcdtype import *
>>> Point = recordtype('Point', 'x y')
>>> pt1 = Point(1.0, 5.0)
>>> pt1 = Point(1.0, 5.0)
>>> pt1.x = 2.0
>>> print(pt1[0])
    2.0

However, I don't know of any form of named list that allows you to add new fields. In this case, you may only want to use a dictionary. The named tuple can be converted into a dictionary by using pT1. ﹣ asdict(), which returns {'x': 1.0, 'y': 5.0} and can be operated by using all the commonly used dictionary functions.

As mentioned earlier, you should View document To get more information that makes up these examples.

#5th floor

namedtuple is a great feature, they are perfect containers for data. When you have to "store" data, you can use tuples or dictionaries, such as:

user = dict(name="John", age=20)

or

user = ("John", 20)

The dictionary method is overwhelming because dictionaries are more volatile and slower than tuples. On the other hand, tuples are immutable and lightweight, but they lack readability for a large number of entries in data fields.

namedtuple is the perfect compromise between these two methods, they have excellent readability, lightness and invariance (and they are polymorphic!).

Posted by kappaluppa on Tue, 17 Dec 2019 21:04:34 -0800