Title: Make ast.dump() not output optional default fields
Type: enhancement Stage: patch review
Components: Library (Lib) Versions: Python 3.8
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: benjamin.peterson, brett.cannon, eamanu, levkivskyi, serhiy.storchaka, yselivanov
Priority: normal Keywords: patch

Created on 2019-03-14 09:48 by serhiy.storchaka, last changed 2019-03-16 06:25 by serhiy.storchaka.

Pull Requests
URL Status Linked Edit
PR 12328 closed eamanu, 2019-03-14 14:35
Messages (6)
msg337907 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2019-03-14 09:48
Currently ast.dump() outputs values for optional fields even if they are equal to defaults. This makes the output unnecessary verbose.

For example (kind and type_comment are optional):

>>> ast.dump(ast.parse('x = 1'))
"Module(body=[Assign(targets=[Name(id='x', ctx=Store())], value=Constant(value=1, kind=None), type_comment=None)], type_ignores=[])"
msg337922 - (view) Author: Emmanuel Arias (eamanu) * Date: 2019-03-14 14:36
Hi @serhiy.storchaka,

I send a patch to Github to review. Let me know if is necessary unittest. 

msg337955 - (view) Author: Brett Cannon (brett.cannon) * (Python committer) Date: 2019-03-14 17:27
@eamanu tests are basically always necessary. :)
msg338030 - (view) Author: Ivan Levkivskyi (levkivskyi) * (Python committer) Date: 2019-03-15 20:33
We can probably also skip `type_ignores` list if it is empty (which will be the case in 99% situations).
msg338033 - (view) Author: Emmanuel Arias (eamanu) * Date: 2019-03-15 20:54
Maybe we can ignore None and [] ?
msg338055 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2019-03-16 06:25
None can not be ignored in Constant(value=None). [] can not be ignored in Tuple(elts=[]).

There is also a problem with using ast.dump() with annotate_fields=False:

>>> from ast import *
>>> dump(Raise(cause=Name(id='B', ctx=Load())), annotate_fields=False)
"Raise(Name('B', Load()))"
>>> dump(Raise(Name('B', Load())))
"Raise(exc=Name(id='B', ctx=Load()))"

For Raise(cause=X) it outputs a string which is evaluated to Raise(exc=X).
Date User Action Args
2019-03-16 06:25:33serhiy.storchakasetmessages: + msg338055
2019-03-15 20:54:42eamanusetmessages: + msg338033
2019-03-15 20:33:20levkivskyisetnosy: + levkivskyi
messages: + msg338030
2019-03-14 17:27:34brett.cannonsetmessages: + msg337955
2019-03-14 14:36:47eamanusetmessages: + msg337922
2019-03-14 14:35:08eamanusetkeywords: + patch
stage: patch review
pull_requests: + pull_request12299
2019-03-14 12:19:06eamanusetnosy: + eamanu
2019-03-14 09:48:05serhiy.storchakacreate