Tuple question

Alex Martelli aleaxit at yahoo.com
Sat Sep 4 15:58:08 CEST 2004

Andrew Durdin <adurdin at gmail.com> wrote:
> > and time now return, may be a different issue.  Not sure why we never
> > made declaring such pseudotuples as usertypes as easy as it should be, a
> > custom metaclass in some stdlib module shd be enough.  But tuples whose
> Such "pseudotuples" are easy enough to implement. Since I'm not all
> that crash hot with metaclasses, I just made a tuple subclass (see
> below). Would a metaclass implementation offer any significant
> benefits over a subclass?

I think of a tuple with a given sequence of names for its fields as a
type (a subclass of tuple, sure).  For example, the name->index
correspondence for all the pseudotuples-with-9-items returned by module
time is just the same one -- why would I want to carry around that
dictionary for each INSTANCE of a time-pseudotuple, rather than having
it once and for all in the type?  So I'd have, say:

example_type = tuple_with_names('foo', 'bar', 'baz')
assert issubclass(example_type, tuple)

and then I could make as many instances of this subclass of tuple as
needed, with a call like either example_type(1,2,3) or
example_type(baz=3,foo=1,bar=2) [the first form would accept 3
positional arguments, the second one 3 named arguments -- they're all
needed of course, but passing them as named will often result in clearer
and more readable application-level code].

You prefer to specify the names every time you make an instance and
build and carry the needed name->index dict along with each instance.
Ah well, I guess that's OK, but I don't really see the advantage
compared to the custom-metaclass approach.

> (Submitted to the Cookbook: recipe #303439)

Great, thanks -- I should get the snapshot tomorrow (or whenever they do
start working again over in Vancouver, since I get it from
ActiveState:-) and I'll be happy to consider presenting your approach
(and a custom metaclass for contrast;-).


More information about the Python-list mailing list