Paul Rubin wrote:
YAML looks to me to be completely insane, even compared to Python lists. I think it would be great if the Python library exposed an interface for parsing constant list and dict expressions, e.g.:
[1, 2, 'Joe Smith', 8237972883334L, # comment {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment 'xyzzy', [3, 5, [3.14159, 2.71828, []]]]
I don't see what YAML accomplishes that something like the above wouldn't.
Note that all the values in the above have to be constant literals. Don't suggest using eval. That would be a huge security hole.
Not hard at all, thanks to compiler.ast:
>>> import compiler
...
>>> class AbstractVisitor(object):
... def __init__(self):
... self._cache = {} # dispatch table
...
... def visit(self, node,**kw):
... cls = node.__class__
... meth = self._cache.setdefault(cls,
... getattr(self,'visit'+cls.__name__,self.default))
... return meth(node, **kw)
...
... def default(self, node, **kw):
... for child in node.getChildNodes():
... return self.visit(child, **kw)
...
>>> class ConstEval(AbstractVisitor):
... def visitConst(self, node, **kw):
... return node.value
...
... def visitName(self,node, **kw):
... raise NameError, "Names are not resolved"
...
... def visitDict(self,node,**kw):
... return dict([(self.visit(k),self.visit(v)) for k,v in node.items])
...
... def visitTuple(self,node, **kw):
... return tuple(self.visit(i) for i in node.nodes)
...
... def visitList(self,node, **kw):
... return [self.visit(i) for i in node.nodes]
...
>>> ast = compiler.parse(source,"eval")
>>> walker = ConstEval()
>>> walker.visit(ast)
[1, 2, 'Joe Smith', 8237972883334L, {'Favorite fruits': ['apple', 'banana', 'pear']}, 'xyzzy', [3, 5, [3.1415899999999999, 2.71828, []]]]
Add sugar to taste
Regards
Michael
-- http://mail.python.org/mailman/listinfo/python-list