python / python/cpython

email.message.Message.add_header behavior differs from Message[header]=v

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

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

stdlib topic-email triaged type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:

Attempting to copy headers from an existing message to a new (to-be-cleaned copy of the original) message, I iterated over the old message, using something like

for h, v in oldmsg.items():
    newmsg.add_header(h, v)

which works for many of the test-messages in my test Maildir folder, but errors out on certain messages with

    newmsg.add_header(h, v)
    ~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "/usr/local/lib/python3.13/email/message.py", line 587, in add_header
    self[_name] = SEMISPACE.join(parts)
                  ~~~~~~~~~~~~~~^^^^^^^
TypeError: sequence item 0: expected str instance, Header found

It appears that elements in msg.items() can produce a mixed-content list containing both (str, str) and (str, Header) elements; but add_header doesn't like receiving a Header object as a value, only str.

If I change it to use the .__setitem__() method function:

for h, v in oldmsg.items():
    newmsg[h] = v

it appears to work fine, appending the header that .items() gave me.

According to the .add_header() documentation, it should behave similar to the .__setitem__() method:

This method is similar to __setitem__() except that additional header parameters can be provided as keyword arguments. _name is the header field to add and _value is the primary value for the header.

The fix would involve making add_header accept the same sorts of Header values as __setitem__, or at least align the output of msg.items() with the types that msg.set_header() accepts. If not aligned, at a bare minimum, the documentation should reflect the difference in accepted value types (str vs Header)

This may also have tie-ins with similar Issues here:

  • #65294
  • #91957
  • #101090

(manifested on 3.13 on OpenBSD, but it's standard-library stuff that would likely manifest on any OS)

CPython versions tested on:

3.13

Operating systems tested on:

Other

Linked PRs
  • gh-151458

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

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

はじめの一歩

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

調査の方向性

まずリンクされた PR gh-151458 を確認し、その後 email/message.py の Message.add_header 周辺を調べ、Message.setitem および items() と比較します。報告にある str/Header の混在ケースを再現してください。動作が一致するか、受け入れられる値型の違いが文書化されれば完了です。

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

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
25/100

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

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