Add comments parsing flag to ast.parse

Feature or enhancement

Add a flag to ast.parse that signals it to parse comments for directives given to various static analysis tools like PyRight, MyPy, Pylint, etc.


Currently, ast.parse produces directives for type: ignore only, which all type checkers respond to. PyRight reacts to its own special pyright: ignore flag to disambiguate type errors that are specific to it. MyPy cannot easily implement a similar flag since it depends on ast.parse. Yet a mypy: ignore directive is needed.

A concrete interface is proposed here by @jab.

(I may have jumped the gun in posting an issue to cpython, but hoping to get some discussion about this and editing or deleting that issue as appropriate.)


I swear this has come up before, specifically around a way to include an annotation on nodes if they have a relevant # ignore-like comment.

This one by Guido?

I thought that typed_ast (originally not mine!) has long been superseded by the stdlib feature you’re mentioning. The project still sees some activity, though it doesn’t look it supports anything newer than 3.7.

I’m not sure that the directove_comments=True flag to ast.parse(), as proposed, is really going to work – it would seem to have a high rate of false positives if it just looks for any comment of the form # <namespace>: <text> (lots of non-directive comments will look like that). Maybe a list of namespaces the caller is interested in could be provided?