Skip to content

email: UnboundLocalError parsing a Message-ID whose domain literal starts with whitespace #161966

Done

Description

@Broyojo

Bug report

email._header_value_parser.parse_message_id and parse_message_ids raise UnboundLocalError when the part after @ is a domain literal that starts with a space or tab, such as <a@[ x]>. Because of this, reading Message-ID, References or In-Reply-To from such a message with policy.default raises instead of returning a header with a defect. gh-134152 fixed the same error for an empty literal (<T@[), but a literal that begins with whitespace still reaches the same code.

import email
from email import policy
from email._header_value_parser import parse_message_id

parse_message_id('<a@[ x]>')

msg = email.message_from_string('Message-ID: <a@[ x]>\n\nbody\n', policy=policy.default)
msg['Message-ID']

Actual:

UnboundLocalError: cannot access local variable 'pos' where it is not associated with a value

Expected: no exception. The header should parse with a defect, the same way <a@[x ]> already does (it gives a MessageID with an ObsoleteHeaderDefect, "obsolete id-right in msg-id").

The cause is in _get_ptext_to_endchars: when value starts with whitespace, the first fragment from _wsp_splitter is empty, the for pos in ... loop never runs, and the else clause reads pos before it is assigned.

CPython versions tested on:

3.15, CPython main branch

Operating systems tested on:

Linux


Found while building a Lean 4 model of CPython (https://broyojo.com/python-formalization/). AI tools (Claude) helped investigate the findings and prepare this report. The examples were rerun on CPython 3.15.2 and main, and the report received technical review. Record: textlibs-email-msgid-no-fold-literal-space

Linked PRs

Activity

  1. added
    type-bug
    stdlib
    on Nov 14, 2026
  2. added 3 commits that reference this issue on Dec 1, 2026
  3. bitdancer commented on Dec 1, 2026

    @bitdancer
    Member

    Thanks, closed by #161967.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtopic-emailtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions