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

George Sakkis george.sakkis at gmail.com
Wed Oct 21 14:02:18 CEST 2009

On Wed, Oct 21, 2009 at 12:13 PM, Eero Nevalainen
<eero.nevalainen at indagon.com> wrote:
> 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.
> 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?

You can override the __new__ method in your type:

class Foo(namedtuple('Foo', 'a b c')):
    def __new__(cls, a, b, c):
        # input validation and/or adaptation
        a = int(a)
        b = float(b)
        c = list(c)
        return super(Foo,cls).__new__(cls,a,b,c)

>>> Foo(1, 2, 'xyz')
Foo(a=1, b=2.0, c=['x', 'y', 'z'])

It's not perfect (the super call is ugly, in 2.x at least) but it works.


More information about the Python-ideas mailing list