[Python-Dev] What's a PyStructSequence ?

nickm@alum.mit.edu nickm@alum.mit.edu
Wed, 28 Nov 2001 20:27:36 -0500


Marc-Andre Lemburg wrote:
> "Martin v. Loewis" wrote:
> > > > A bug report on SF made me aware of an apparently new type in Python
> > > > called PyStructSequence. There are no docs on the type (at least
> > > not in the usual places).
> > >
> > > Is it official yet ?
> > > It will ship as part of Python 2.2, if that is what you are
> > asking. os.stat is documented to return one of these (if you read it
> > carefully).
>
>Wouldn't it make sense to expose this object in Python,
>e.g. by contructing it from a dictionary of string mappings ?
>
>(The type constructor is not made available in bltinmodule.c.)

Hi, all.  I'm not subscribed to python-dev, but I'm the author of the
original patch, and I thought I should comment.

If you look closely, you'll find that PyStructSequence is not a type
itself, but rather a tool used to construct new tuple/struct hybrid
types, like the results of os.stat and time.gmtime.

In reality, PyStructSequence is only a set of common implementation
logic for a set of other types, including os.stat_result,
os.statvfs_result, and time.struct_time.

There are a few possible objections to this scheme:

      Q. Nick, why didn't you make it a _real_ metatype?

      A. Writing a real metatype in C was beyond my Python
         abilities. If anybody wants to, I'd be thrilled.a

    Q. Okay, so why not expose it to python?

    A. Because it isn't a real metatype.  Every type that uses it _is_
       exposed to python.

       I think this isn't a problem, because it's way easier to
       re-implement PyStructSequence in Python than it is to turn it
       into a metatype.

    Q. If it's so easy to write in Python, why not do it that way?

    A. Because there are fringe benefits to doing it in C.  

       For example, on some Unix machines (such as Linux), struct stat
       has some attributes that don't correspond to any elements of
       the old tuple view.  To expose (say) st_rdev to Python code at
       all, you'd need to change the result of posix.stat... but this
       would break code that used posix.stat directly.

       But because PyStructSequence is written in C, posix.stat can
       return an augmented tuple/struct hybrid that (when accessed as
       a tuple) still has 10 elements, but also exposes st_rdev as an
       attribute.

HTH,
-- 
Nick Mathewson
<nickm@alum.mit.edu>