[Python-ideas] Proposal to add new built-in struct (was: Add kwargs to built-in function object)

Brett Cannon brett at python.org
Fri May 23 00:10:02 CEST 2008


On Thu, May 22, 2008 at 2:42 PM, Brandon Mintern <bmintern at gmail.com> wrote:
> This is a proposal to add a new built-in named struct:
>
> struct(**kwargs)
>    Return a struct object which has the attributes given in kwargs.
>
> The name is really unimportant, and I'm open to other ideas, but I
> feel that many people have a good idea of what a struct is, and
> accessing an object returned from struct would look identical to the
> access of a struct in C, so it seems appropriate to me.
>
>
> The rationale:
>
> It is often helpful to package related information together in order
> to make passing the information to various functions more convenient.
> The easiest ways (currently) to package such information is to put it
> into a tuple (the easiest) or a dict.
>
> Putting the information into a tuple may be easy initially, but it has
> high costs later on as it becomes hard to remember what order the
> information is in, and to someone reading the code, the intent of the
> code is far from clear.
>
> Putting the information in a dict is a bit harder than a tuple, but
> since it is more readable later on than a tuple, this method is often
> used. Still, the access pattern is more cumbersome than it could be;
> foo["bar"] is more cumbersome than, say, foo.bar. This is especially
> the case if you have a dict or list of foos, where you then have to
> use foos[i]["bar"].
>

So you save three characters? I don't call that cumbersome.

> Both tuple and dict solutions suffer down the line when the
> information gets to be complicated enough to warrant a class of its
> own. It involves changing both the spot in the code where the
> information is created (to use the new class constructor), as well as
> changing every single field access in the code (changing every foo[0]
> or foo["bar"] to foo.bar).
>
> An alternative is to use NamedTuple, NamedDict, NamedList, or to
> create your own class. As long as these are more complicated to use
> than a tuple or a dict, however, they are not likely to be used for
> this purpose. Another problem is that all of these methods require you
> to go to the trouble of thinking of a name for your class, and if you
> later decide to add more information to your packaged object, you have
> to make two changes (in the list of attributes / constructor and in
> the place where you instantiate your object).
>

Thinking of a name for your class is not difficult, especially if you
keep it private to the module, class, function, etc.

This does not strike me as useful enough to have as a built-in. It
would be better placed in the stdlib.

-Brett



More information about the Python-ideas mailing list