[Python-Dev] What's a PyStructSequence ?

Martin v. Loewis martin@v.loewis.de
Tue, 27 Nov 2001 22:09:38 +0100


> Hmm, isn't the trick with this type that you can access
> the various elements as attributes *and* using index 
> notation ?

Indeed. In Py 2.2, you can do that two ways:

A) indexmap = {'st_dev':0, 'st_ino':1} # etc
   class StatResult(tuple):
      def __getattr__(self,name):
        return self[indexmap[name]]

B) fields = ['st_dev', 'st_ino'] #etc
   class StatResult(UserList.UserList):
      def __init__(self, dev, ino):
        self.st_dev = dev
        self.st_ino = ino

      def __getattr__(self, name):
        if name=="data":
          return [getattr(self,fname) for fname in fields]
        raise AttributeError, name

      def __setattr__(self, name, value):
        if name=="data":
          raise AttributeError, "data is read-only"
        self.__dict__[name] = value

> Also, why should we hide something useful from the Python programmer
> if it's there anyway ?

Because it has unknown limitations (atleast, they are unknown to me at
the moment; I probably could report them if I searched long enough).

Regards,
Martin