Keeping a list of records with named fields that can be updated

songbird songbird at anthive.com
Thu Dec 15 08:41:57 EST 2022


Peter Otten wrote:
>
> While I think what you need is a database instead of the collection of
> csv files the way to alter namedtuples is to create  a new one:

  the files are coming from the web site that stores the
accounts.  i already have manually created files from many
years ago with some of the same information but to go back
and reformat all of those would be a lot of work.  it is
much easier to just take the files as supplied and process
them if i can do that instead.

  i do know database stuff well enough but this is fairly
simple math and i'd like to avoid creating yet another
copy in yet another format to have to deal with.


> >>> from collections import namedtuple
> >>> Row = namedtuple("Row", "foo bar baz")
> >>> row = Row(1, 2, 3)
> >>> row._replace(bar=42)
> Row(foo=1, bar=42, baz=3)
>
> An alternative would be dataclasses where basic usage is just as easy:
>
> >>> from dataclasses import make_dataclass
> >>> Row = make_dataclass("Row", "foo bar baz".split())
> >>> row = Row(1, 2, 3)
> >>> row
> Row(foo=1, bar=2, baz=3)
> >>> row.bar = 42
> >>> row
> Row(foo=1, bar=42, baz=3)

  thanks, i'll give these a try.  :)


  songbird


More information about the Python-list mailing list