[issue33850] Json.dump() bug when using generator

Walter Dörwald report at bugs.python.org
Wed Jun 13 09:00:02 EDT 2018


Walter Dörwald <walter at livinglogic.de> added the comment:

The problem here is that StreamArray lies about the length of the iterator. This confuses json.encoder._make_iterencode._iterencode_list(), (which is called by json.dump()), because it first does a check for "if not lst" and then assumes in the loop that it will be entered at least once.

(Note that json.dumps() doesn't have that problem, because it calls JSONEncoder.encode() with _one_shot=True which leads to a totally different code path).

We could declare that bug as "don't do that then", but the problem is easily solvable, because we can check whether the loop was entered. The attached patch should do the trick.

An even better approach would IMHO be, that the encoder supports a special flag that enables JSON serialization of generators directly, so it's no longer required to masquerade generators as list

----------
keywords: +patch
nosy: +doerwalter
resolution: not a bug -> 
status: closed -> open
Added file: https://bugs.python.org/file47640/json-dump-generators-bug.diff

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue33850>
_______________________________________


More information about the Python-bugs-list mailing list