#2983: Proposal to add util.parseargs
---------------------+------------------------------------------------------
 Reporter:  athomas  |        Owner:  jonas
     Type:  defect   |       Status:  new  
 Priority:  high     |    Milestone:  0.10 
Component:  general  |      Version:  0.9.4
 Severity:  normal   |   Resolution:       
 Keywords:           |  
---------------------+------------------------------------------------------
Comment (by athomas):

 How about this implementation. It handles normal Python basic types and
 has the same calling convention and return type as the above.

 {{{
 #!python
 def parse_args(args):
     import compiler

     def get_value(node):
         if isinstance(node, compiler.ast.Name):
             return node.name
         elif isinstance(node, compiler.ast.Const):
             return node.value
         elif isinstance(node, compiler.ast.Tuple) or \
              isinstance(node, compiler.ast.List):
             return tuple([get_value(el) for el in node.nodes])
         elif isinstance(node, compiler.ast.Dict):
             return dict([(get_value(k), get_value(v)) for k, v in
 node.items])
         raise ValueError('invalid arguments near %s' % str(node))

     largs = []
     kwargs = {}
     expr = compiler.parse('mock(%s)' % args, 'eval')
     for node in expr.getChildNodes()[0].args:
         if isinstance(node, compiler.ast.Keyword):
             kwargs[node.name] = get_value(node.expr)
         else:
             largs.append(get_value(node))
     return largs, kwargs
 }}}

-- 
Ticket URL: <http://projects.edgewall.com/trac/ticket/2983>
The Trac Project <http://trac.edgewall.com/>
_______________________________________________
Trac-Tickets mailing list
[email protected]
http://lists.edgewall.com/mailman/listinfo/trac-tickets

Reply via email to