Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python counterpart to an Ada record / C++ struct type?

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?

like image 425
Greg Avatar asked Oct 27 '25 01:10

Greg


2 Answers

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.

like image 56
Don O'Donnell Avatar answered Oct 28 '25 16:10

Don O'Donnell


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.

like image 42
Ignacio Vazquez-Abrams Avatar answered Oct 28 '25 17:10

Ignacio Vazquez-Abrams