[Python-ideas] Syntax for making stuct / record / namedtuples

Eero Nevalainen eero.nevalainen at indagon.com
Wed Oct 21 13:15:10 CEST 2009


wxyarv wrote:
>>>Whenever my module A needs to pass a lot of data to module B, I find
>>>myself making a factory function in module B for creating the
> datastructures
>>>
>>>def my_factory_function(a, b, c):
>>>     # input checking
>>>     res.a = a
>>>     res.b = b
>>>     res.c = c
>>>     return res
>>>
>>>I believe this is fairly common.
>>>
>>>Since the fields are already defined in the function signature, I'd
>>>prefer to not repeat myself and write something like this:
>>>
>>>def my_factory_function(a, b, c):
>>>     args = locals()
>>>     # input checking
>>>     return namedtuple('MyTypeName', args)
>>>
>>>
>>>This would perceivably be possible, if locals() returned an OrderedDict
>>>and an appropriate namedtuple factory function was added.
>>>
>>>related discussion is in:
>>>http://kbyanc.blogspot.com/2007/07/python-aggregating-function-arguments.html
>>>http://code.activestate.com/recipes/500261/
>>>
>>>Does this seem familiar or useful to anyone besides me?
> in current syntax, res.a = a is not allowed, if res is a dict, the
> right syntax is res['a'] = a. in some languages, res.a equals
> res['a'], but not in python. (and isn't possible in Python, because
> there are many disadvantage to make this.).
> so, if you need put arguments into a dict, you can do this:
> def my_factory_function(**arg):
>     # input check
>     return arg
> arg is a dict.
> and, if res is a class, you are setting the attribute of res. you can
> also:
> def my_factory_function(**arg):
>     # input check
>     res.__dict__.update(arg)
>     return res
> a named tuple is just a dict (I think :-)

Right. I probably didn't express myself too well. The current recipe for
'structs' is here http://docs.python.org/tutorial/classes.html#odds-and-ends

make an empty class, and assign fields as necessary.

I prefer using factory functions, since I then I can define in a single
place, what the 'struct' is supposed to contain, and the function
signature will conveniently raise errors if I've made changes in module
B, but not A.

The same boilerplate code is also in all normal class init methods, you
list the stuff once in the __init__ method arguments, then you list them
again when you assign them, and I'm just wondering why do I have to
repeat myself.


As for named tuples, I quote
http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields

"Named tuple instances do not have per-instance dictionaries, so they
are lightweight and require no more memory than regular tuples."

-- 
Eero Nevalainen




More information about the Python-ideas mailing list