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

Michael Foord fuzzyman at gmail.com
Wed Oct 21 13:50:16 CEST 2009


2009/10/21 Eero Nevalainen <eero.nevalainen at indagon.com>

> From the (creative) laziness department:
>
> 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.
>
>
The C# syntax for this  (anonymous types new in C# 3.0) is:

    var obj = new { prod.Color, prod.Price }

C# creates what is effectively a named tuple parsing the field names from
the way you construct it. The closest Python syntax would be something like:

    obj = {Color=foo, Price=bar}

Or as we seem to be overloading curly braces a great deal now, how about:

    obj = (Color=foo, Price=bar)

All the best,

Michael


> 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?
>
> --
> Eero Nevalainen
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 
http://www.ironpythoninaction.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20091021/0816faac/attachment.html>


More information about the Python-ideas mailing list