SeqAttr
June 03, 2006

Sequenced attributes are useful for types that behave as sequences, but provide direct attribute access. For examples of such types, see time.struct_time of the result of os.fstat.

Note: since the inclusion of namedtuple, this recipe is considered deprecated.

==Code==

class seqattr(object):
    __slots__ = ["index"]
    def __init__(self, index):
        self.index= index
    def __repr__(self):
        return "<seqattr(%s)>" % (self.index,)
    def __get__(self, obj, cls):
        if obj is None:
            return self
        return obj[self.index]
    def __set__(self, obj, value):
        obj[self.index] = value

Example

>>> class struct_time(list):
...     year = seqattr(0)
...     month = seqattr(1)
...     day = seqattr(2)
...     hour = seqattr(3)
...     min = seqattr(4)
...     sec = seqattr(5)
...     weakday = seqattr(6)
...     yearday = seqattr(7)
...     daylight_saving = seqattr(8)
...
>>>
>>> struct_time.month
<seqattr(1)>
>>>
>>> s = struct_time((2006, 6, 2, 23, 56, 1, 4, 153, 0))
>>> s
[2006, 6, 2, 23, 56, 1, 4, 153, 0]
>>> s.month
6
>>> s.month = 8
>>> s
[2006, 8, 2, 23, 56, 1, 4, 153, 0]