Python: Extending a predefined named tuple

后端 未结 3 2009
-上瘾入骨i
-上瘾入骨i 2020-12-14 17:06

I have the following named tuple:

from collections import namedtuple
ReadElement = namedtuple(\'ReadElement\', \'address value\')

and then

3条回答
  •  被撕碎了的回忆
    2020-12-14 17:22

    It's quite easy to knock something together that allows you to compose namedtuples from other namedtuples as well as introduce new fields.

    def extended_namedtuple(name, source_fields):
        assert isinstance(source_fields, list)
        new_type_fields = []
        for f in source_fields:
            try:
                new_type_fields.extend(f._fields)
            except:
                new_type_fields.append(f) 
        return namedtuple(name, new_type_fields) 
    
    # source types
    Name = namedtuple('Name', ['first_name', 'last_name'])
    Address = namedtuple('Address', ['address_line1', 'city'])
    # new type uses source types and adds additional ID field
    Customer = extended_namedtuple('Customer', ['ID', Name, Address])
    # using the new type
    cust1 = Customer(1, 'Banana', 'Man', '29 Acacia Road', 'Nuttytown')
    print(cust1)
    

    This outputs the following :

    Customer(ID=1, first_name='Banana', last_name='Man', address_line1='29 Acacia Road', city='Nuttytown')
    

提交回复
热议问题