[docs] [issue34000] Document when compile returns a code object v. AST

Geoffrey Sneddon report at bugs.python.org
Fri Jun 29 11:48:53 EDT 2018

New submission from Geoffrey Sneddon <geoffers+pythonbugs at gmail.com>:

The compile built-in documentation says:

> Compile the source into a code or AST object.

It doesn't however go on to say when it returns each!

It does however note:

> If you want to parse Python code into its AST representation, see ast.parse().

So compile can compile the source into an AST object, but if I want to parse Python code into an AST I should use ast.parse?

As far as I can tell, this goes back to Python 2.5: https://docs.python.org/2/whatsnew/2.5.html#build-and-c-api-changes

>From the What's New page:

> It’s possible for Python code to obtain AST objects by using the compile() built-in and specifying _ast.PyCF_ONLY_AST as the value of the flags parameter

So that would seem to be the case when compile returns an AST!

Interestingly, the implementation of ast.parse *literally just calls compile* (https://github.com/python/cpython/blob/58ed7307ea0b5c5aa052291ebc3030f314f938d8/Lib/ast.py#L30-L35).

Note, however, this means a further part of the compile documentation is wrong:

> The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source.

flags is therefore something more general than just controlling which future statements affect the source, given it also controls the output type of the function.

In short, we should:

 * document the flags argument can take _ast.PyCF_ONLY_AST *or* change the documentation to say it returns a code object (and not an AST object)

assignee: docs at python
components: Documentation
messages: 320721
nosy: docs at python, gsnedders
priority: normal
severity: normal
status: open
title: Document when compile returns a code object v. AST
versions: Python 2.7, Python 3.7

Python tracker <report at bugs.python.org>

More information about the docs mailing list