Reputation: 1500
Suppose I am recording data and want to associate some number of data elements, such that each recorded set always has a fixed composition, i.e. no missing fields.
Most of my experience as a programmer is with Ada or C/C++ variants. In Ada, I would use a record type and aggregate assignment, so that when the record type was updated with new fields, anyone using the record would be notified by the compiler. In C++, chances are I would use a storage class and constructor to do something similar.
What is the appropriate way to handle a similar situation in Python? Is this a case where classes are the proper answer, or is there a lighter weight analog to the Ada record?
An additional thought, both Ada records and C++ constructors allow for default initialization values. Is there a Python solution to the above question which provides that capability as well?
Upvotes: 4
Views: 1150
Reputation: 4728
A namedtuple (from the collections library) may suit your purposes. It is basically a tuple which allows reference to fields by name as well as index position. So it's a fixed structure of ordered named fields. It's also lightweight in that it uses slots
to define field names thus eliminating the need to carry a dictionary in every instance.
A typical use case is to define a point:
from collections import namedtuple
Point = namedtuple("Point", "x y")
p1 = Point(x=11, y=22)
It's main drawback is that, being a tuple, it is immutable. But there is a method, replace
which allows you to replace one or more fields with new values, but a new instance is created in the process.
There is also a mutable version of namedtuple available at ActiveState Python Recipes 576555 called records which permits direct field changes. I've used it and can vouch that it works well.
Upvotes: 5
Reputation: 799230
A dictionary is the classical way to do this in Python. It can't enforce that a value must exist though, and doesn't do initial values.
config = {'maxusers': 20, 'port': 2345, 'quota': 20480000}
collections.namedtuple()
is another option in versions of Python that support it.
Upvotes: 3