Example Analysis of Named Tuples in python Tutorial

  • 2021-12-04 19:12:12
  • OfStack

Directory

collections. namedtuple () is actually a factory method that returns a subclass of the standard tuple type in python. If we give it a type name and the corresponding field, it will return an instantiable class and pass in values for the fields you have defined.


from collections import namedtuple
Subscriber = namedtuble('Subscriber', ['addr', 'joined'])
sub = Subscriber('jonesy@example.com', '2012-10-19')
print(sub)
# Subscriber(addr='jonesy@example.com', joined='2012-10-19') 
print(sub.addr)
# 'jonesy@example.com'
print(sub.joined)
# '2012-10-19'

Although the instance of namedtuple looks like an ordinary class instance, its instance is interchangeable with ordinary tuples and supports all operations supported by ordinary tuples. For example, indexing and decomposition


print(len(sub))
# 2
addr, joined = sub
print(addr)
# 'jonesy@example.com' 
print(joined)
# '2012-10-19'

The main function of named tuples is to decouple the code from the position of elements it controls. So, if you get a large list of tuples from a database call and access the data through the location of the elements, if you add a new column of data to the form, the code will crash. However, if the returned tuple is transformed into a named tuple first, there will be no problem.


from collections import namedtuple
 
Stock = namedtuple('Stock', ['name', 'shares', 'price'])
def compute_cost(records):
    total = 0.0
    for rec in records:
        s = Stock(*rec)
        total += s.shares * s.price
        #  If this is  total += s[1] * s.[2]  Then the data 1 Change, and the code is wrong 
    return total

Note: namedtuple is immutable (immutable)


s = Stock('ACEM', 100, 123.45)
print(s)
# Stock(name='ACME', share=100, price=123.45)
s.share = 75
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: can't set attribute

If you need to modify any attributes, you can do so by using the _ replace () method of the namedtuple instance, which creates a brand new named tuple and replaces the corresponding value.


s = s._replace(share=75)
print(s)
# Stock(name='ACME', share=75, price=123.45)

The _ replace () method has a subtle use as an easy way to populate named tuples with optional or missing fields. To do this, first create a "prototype" tuple with the default value, and then use the _ replace () method to create a new instance, replacing the corresponding value


from collection import namedtuple
Stock = namedtuple('Stock', ['name', 'share', 'price', 'data', 'time'])
# Create a prototype instance
stock_prototype = Stock('', 0, 0.0, None, NOne) 
# Function to convert a dictionary to a Stock
def dict_to_stock(s):
    return stock_prototype.replace(**s)

Let's demonstrate how the above code works under 1:


>>> a = {'name': 'ACME', 'shares': 100, 'price': 123.45}
>>> dict_to_stock(a)
Stock(name='ACME', shares=100, price=123.45, date=None, time=None)
>>> b = {'name': 'ACME', 'shares': 100, 'price': 123.45, 'date': '12/17/2012'}
>>> dict_to_stock(b)
Stock(name='ACME', shares=100, price=123.45, date='12/17/2012', time=None)

If our goal is to define an efficient data structure and various instance properties will be modified in the future, then using namedtuple is not the best choice

The above is the python tutorial named tuple sample analysis details, more about the python named tuple information please pay attention to other related articles on this site!


Related articles: