[Python-Dev] Recent experience with the _ast module (original) (raw)

Collin Winter collinw at gmail.com
Sat Feb 17 02:01:20 CET 2007


On 2/14/07, "Martin v. Löwis" <martin at v.loewis.de> wrote:

Collin Winter schrieb: > What's inconsistent about it? That classes are being used for the > ast.{Add,Sub,Mult,etc} names?

Exactly. These aren't names - they are nodes in the tree. All nodes are instances of ast.AST. > I don't see the need for both ast.Add and ast.Add.singleton or > ast.add or however else it might be spelled. I'd be perfectly happy > doing something like "ast.Add = object()" (when initializing the ast > module), so long as I can write "node.op is ast.Add", "node.op == > ast.Add", or something equally brief and to-the-point. Would you like to do the same for Pass, Break, Continue, and Ellipsis? They are also "just names". If you make ast.Add the entry in the tree itself, why not ast.Break? Or, if you have a way to deal with ast.Break, why can't the same way work for ast.Add?

But Pass, Break, Continue and Ellipsis aren't in the same category as Add, Mult, Div, etc.. The former stand alone, while the only time you'll ever encounter Add, Mult, Mod and co. is in the context of a BoolOp, BinOp or whatever. I could of course add separate visitor methods for each op type to my code generator, but that's a lot of boilerplate code for very little gain. I could use a dispatch table in visitBoolOp, and dispatch like "dispatch[type(node.op)]", but why? In this scenario, node.op doesn't convey any information other than its type. Add, Mult, etc are just values in an enumeration, so why not treat them that way and be able to write "dispatch[node.op]".

So: what if _ast.Add and co. were singleton instances of _ast.AST or even of a subclass of AST, like _ast.Op? That way, we keep the consistency that all AST nodes are instances of _ast.AST and I get the nice property I'm looking for, ie, "node.op is _ast.Mult".

Collin Winter



More information about the Python-Dev mailing list