[CentralOH] A simple class to provide named fields

Steven Huwig steven_h at acm.org
Thu Jan 17 05:49:31 CET 2008


On Jan 16, 2008, at 8:37 PM, Sam Corder 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.

Nothing's wrong with using dictionaries. I did think of a very minor  
advantage of using a class (using a slightly different implementation):


class Record(object):
     __slots__ = []
     """
     A class intended to provide a simple interface for creating objects
     with named fields. That is, instead of returning a tuple and  
indexing
     it or writing a unique class, you can simply do something like:
     a = Record(x=1, y=2)
     a.x # 1
     a.y # 2
     a   # Record(x=1, y=2)
     """
     def __init__ (self, **kwargs):
         for k, v in kwargs.iteritems():
             setattr(self, k, v)

     def __repr__ (self):
         vals = []
         for k in self.__slots__:
             vals.append((k, repr(getattr(self, k))))
         return "%s(%s)" % (self.__class__.__name__,
                            ", ".join(["%s=%s" % field for field in  
vals]))

class Name(Record):
     __slots__ = ['first','last']


 >>> from Record import Name
 >>> me = Name(first="Steven", last="Huwig")
 >>> me
Name(first='Steven', last='Huwig')
 >>> oops = Name(first="Steven", middle="J", last="Huwig")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "Record.py", line 14, in __init__
     setattr(self, k, v)
AttributeError: 'Name' object has no attribute 'middle'
 >>>


Of course everyone knows that the real reason to use __slots__ is to  
cut down on space usage by not allocating __dict__. But for simple  
record types, that's at least as desirable as the attribute  
modification prevention shown above.

-- Steve

P.S. the above __repr__ has the nice property of recreating the same  
value when its output is fed to eval().

P.P.S. I believe there is talk of adding an official record type to  
Python at some point.


More information about the CentralOH mailing list