Why does Python not support a record type natively? It's a matter of having a mutable version of namedtuple.
I could use namedtuple._replace
. But I need to have these records in a collection and since namedtuple._replace
creates another instance, I also need to modify the collection which becomes messy quickly.
Background: I have a device whose attributes I need to get by polling it over TCP/IP. i.e. its representation is a mutable object.
Edit: I have a set of devices for whom I need to poll.
Edit:
I need to iterate through the object displaying its attributes using PyQt. I know I can add special methods like __getitem__
and __iter__
, but I want to know if there is an easier way.
Edit: I would prefer a type whose attribute are fixed (just like they are in my device), but are mutable.
Based on several useful tricks gathered over time, this "frozenclass" decorator does pretty much everything needed: http://pastebin.com/fsuVyM45
Since that code is over 70% documentation and tests, I won't say more here.
Here is a complete mutable namedtuple I made, which behaves like a list and is totally compatible with it.
There's a library similar to namedtuple, but mutable, called recordtype.
Package home: http://pypi.python.org/pypi/recordtype
Simple example:
Simple default value example:
Iterate through the fields of
person1
in order:Python <3.3
You mean something like this?
Note that the methods provided are just a sample of possible methods.
Python ≥3.3 update
You can use
types.SimpleNamespace
:dir(r)
would provide you with the attribute names (filtering out all.startswith("__")
, of course).This can be done using an empty class and instances of it, like this:
In the closely related Existence of mutable named tuple in Python? question 13 tests are used for comparing 6 mutable alternatives to
namedtuple
.The latest namedlist 1.7 passes all of these tests with both Python 2.7 and Python 3.5 as of Jan 11, 2016. It is a pure python implementation.
The second best candidate according to these tests is the
recordclass
which is a C extension. Of course, it depends on your requirements whether a C extension is preferred or not.For further details, especially for the tests, see Existence of mutable named tuple in Python?