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

wxyarv weasley_wx at qq.com
Wed Oct 21 12:16:03 CEST 2009


>>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 :-)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20091021/f3c82da1/attachment.html>


More information about the Python-ideas mailing list