[Python-ideas] Generator syntax hooks?

Nick Coghlan ncoghlan at gmail.com
Thu Aug 10 23:54:05 EDT 2017


On 11 August 2017 at 01:39, Soni L. <fakedme+py at gmail.com> wrote:
> I'm pretty sure I read somewhere that lambdas and generators share their
> syntax, and that syntax is already a subset of python syntax. Would it be
> too hard to expose that with a "simplified AST" API?

We already do, via the "mode" argument to the compile builtin and to ast.parse:

    >>> ast.dump(ast.parse("1000 <= x < 1000000", mode="eval"))
    "Expression(body=Compare(left=Num(n=1000), ops=[LtE(), Lt()],
comparators=[Name(id='x', ctx=Load()), Num(n=1000000)]))"

    >>> ast.parse("import sys", mode="eval")
    Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "/usr/lib64/python3.6/ast.py", line 35, in parse
       return compile(source, filename, mode, PyCF_ONLY_AST)
     File "<unknown>", line 1
       import sys
            ^
    SyntaxError: invalid syntax

It's a large part of the reason why passing strings around has so far
qualified as "good enough" - providing dedicated syntax for it doesn't
actually increase the language's expressiveness all that much, it just
has the potential to make static analysis easier by eagerly rendering
to an AST rather than having that be handled by the function receiving
the argument.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list