Undocumented interaction between kwargs default= and cls= for json.dump() function

オープン
#101,332 コメント 3 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
38/100
issue の種類
ドキュメント
明瞭さ
おおむね明確
活発さ
停滞
技術スタック
python
領域
documentation

調査の方向性

リンクされている json.dump のドキュメントと提供された再現コードから始め、その後、default と cls がどのように連動するかを確認します。両方の kwargs が指定された場合にどの動作が適用されるかを、JSONEncoder.default() と一貫した表現で、ドキュメントが明示的かつ正確に記載していれば完了です。

索引モデルが issue の本文から書いたものです。

説明

docs

Documentation

The current documentation states that "If specified, default should be a function that gets called for objects that can’t otherwise be serialized", and "To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg" (emphasis mine).

This seems to imply that if both default and cls kwargs are provided, the custom JSONEncoder specified for cls will override the function specified for default. (Although honestly it is unclear from the wording what the exact behavior would be if both are specified, since "the default() method" could be referring to the one in the kwarg for dump() or the subclass override in the custom encoder class).

The observed behavior is that the opposite happens: the function specified in the default kwarg will actually override the default() function from the custom JSONEncoder.

Repro steps:

import json
from json import JSONEncoder
from datetime import datetime

class CustomEncoder(JSONEncoder):
    def default(self, o):
        return "foo"

print(json.dumps(datetime.fromisoformat("2023-01-24T12:35:14"), default=lambda x: "bar"))  # prints "bar", as expected
print(json.dumps(datetime.fromisoformat("2023-01-24T12:35:14"), cls=CustomEncoder))  # prints "foo", as expected
print(json.dumps(datetime.fromisoformat("2023-01-24T12:35:14"), cls=CustomEncoder, default=lambda x: "bar"))  # prints "bar" (but documentation seems to imply the _cls_ encoder would override the _default_ function and thus print "foo")
主要言語
Python
スター
77.2k
フォーク
36k
平均マージ
1日 9時間
マージ済み PR(30日)
558

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

python/cpython のほかの issue

python/cpython の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。