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

Brandon Mintern bmintern at gmail.com
Fri May 23 00:53:31 CEST 2008


On Thu, May 22, 2008 at 6:25 PM, Matthew Russell
<matt.horizon5 at gmail.com> wrote:
> How about:
>   collections.attrs(**kwargs)
> or
>   collections.record(**kwargs)

I've used the name "Record" in the past, but when I was trying to
figure out if Python had anything like a C struct, I searched
specifically for "python struct". I'm not sure how many others do the
same, but perhaps using a name like "structure" would be better than
"record"?

(On a side note, see what I mean about the work involved in naming a class? :-)

> I think I prefer the idea of  this being a factory that returns an anonymous
> object as opposed to a class:
>
> def  record(**kwargs):
>     class Record(object):
>           def __init__(self, **kw):
>               for (k, v) in kwargs.items():
>                   setattr(self, k, v)
>     return Record()

I'm guessing that the last line was meant to be "return Record(**kwargs)"

> This is mainly because a class you later substitude for the
> result of record(**kwargs) may later end up wanting to take kwargs as
> optional values which you might not want as instance variables, or even
> posistional arguements.
>
> x = MyThing(x=1,y=2,  default_spam=False)
>
>
> So you could easilty do:
>
> x = MyThing(default_spam=False, **record_obj.__dict__)
>
> Matt

I can see where you're coming from, but this change would mean that
you would no longer be able to inherit from record (or structure, or
whatever). Also, if you're making that many changes to the class, it
wouldn't be too hard to rewrite the initial instantiation to not use
positional parameters with or without kwargs (after rewriting the
constructor, which you would clearly be doing, anyways). Another
caveat is that each call to record() will create an object of a
different class. Thus, if you have the following:

employees = {}
for ssn, fn, ln in employee_data_list:
    employees[ssn] = record(ssn=ssn, first=fn, last=ln)

Then employees[ssn1].__class__ != employees[ssn2].__class__. This
seems like it could be an issue at some point.

Brandon



More information about the Python-ideas mailing list