[CentralOH] A simple class to provide named fields
Brandon Mintern
bmintern at gmail.com
Thu Jan 17 13:24:26 CET 2008
On Jan 16, 2008 8:37 PM, Sam Corder <samus at codeargyle.com> wrote:
> I know the idea here is to avoid using indexes on tuples but what is wrong with using a good old fashioned dictionary with strings as keys? I know the syntax isn't as pretty as a.x but it accomplishes the same thing without the need for a utility class.
For me, "the syntax isn't as pretty" is a good enough reason. Anything
that saves typing and increases clarity without much more effort is a
winner for me. Let's compare:
a = Record(x=1, y=2)
a.x
a.y
a = {"x": 1, "y": 2}
a["x"]
a["y"]
It seems to me that the Record one is no harder to create (probably
even easier with a higher number of fields, since you don't need to
type the quotation marks), and later accesses are much clearer. Is "a"
really a dictionary? No, it's a collection of data, and I think the
a.x syntax says that much clearer than the dictionary accesses.
That's not to mention when you have my initial use case in mind: a
dictionary where a key references such a record:
employees = {}
for first, last, ssn, salary in some_data:
employees[ssn] = Record(first=first, last=last, salary=salary)
# compared to
employees[ssn] = {"first": first, "last": last, "salary": salary}
employees[12345678].first
# compared to
employees[12345678]["first"]
To me, the very last line above is starting to get a bit ugly, but
maybe I'm just focusing too much on details.
More information about the CentralOH
mailing list