Painful?: Using the ast module for metaprogramming

"Martin v. Löwis" martin at v.loewis.de
Wed Apr 8 15:32:30 EDT 2009


> I see how it avoids needing to look at the parent node in general, but
> if we were compiling by recursively descending through the AST, then
> we would know whether Name's would be loads or stores by the time we
> got to them (we would already had to have visited an encompassing
> assignment or expression)

Python's compiler does recursively descend. However, it is still
more convenient to allow uniform processing of expressions, rather
than having parameters passed down into the visitor functions.

> except in the case of your a = b = c
> expression, which I'm curious how Python handles. The natural answer
> is for assignment to be an expression (so b = c returns the new value
> of b). But Python doesn't do that, so then I'd expect we'd have some
> third ast.LoadAndStore() option for b, but examining ast.parse's
> behavior it looks like it chooses Store...

No, the value of b is never read in this assignment. I'm not quite
sure whether you are aware what the *actual* semantics of this
assignment is; it is equivalent to

 tmp = c
 a = tmp
 b = tmp

(so the assignment to a happens first), and neither a nor b is
being read. So it's simple stores into both a and b.

>>> -Why can't orelse for ast.If and ast.While default to empty []?
>> You want to store None? That would be a type error; orelse is
>> specified as "stmt*". So it must be a list.
> 
> A list is actually what I want, an empty one. The problem is that
> ast.While and ast.If's constructors default to the opposite,
> orelse=None. Same with keywords and args for ast.Call. Admittedly,
> adding orelse=[] to the constructor calls isn't terribly burdensome,
> but it does make already obfuscated looking AST mangling code even
> worse.

Ah, that could be fixed. Please contribute a patch.

>>> -Why can't I eval a functiondef to get back a function object?
>> Because a definition is not an expression. You can only eval
>> expressions.
> 
> I understand that if function definitions were expressions, because of
> the whitespace syntax there wouldn't be a way to express an assignment
> to such an expression. But, why would it be problematic to let them be
> expressions anyway?

This would be a significant change to the compiler, which would have
to learn what bytecodes to compile it to. Feel free to discuss this
on python-ideas.

Regards,
Martin



More information about the Python-list mailing list