Skip to content

Handle empty import_namespaces like import_names in metadata round-trip - #1373

Open
sueun-dev wants to merge 2 commits into
pypa:mainfrom
sueun-dev:fix-empty-import-namespaces
Open

sueun-dev wants to merge 2 commits into
pypa:mainfrom
sueun-dev:fix-empty-import-namespaces

Conversation

@sueun-dev

Copy link
Copy Markdown

import_names and import_namespaces (both added in Metadata 2.5 / PEP 794) share a processor and are validated the same way, but only import_names special-cases the empty-list value. import_namespaces does not, so on 26.3:

  • Metadata.from_raw({..., "import_namespaces": []}) is accepted, but as_rfc822() drops the field entirely, and parsing the output back gives None instead of [].
  • A bare Import-Namespace: header raises invalid or unparsed metadata on parse: the value [""] reaches _process_import_names, where "".isidentifier() is false. A bare Import-Name: parses to [].

Both special cases ([""] -> [] on parse, [] -> "" on write) were added for import_names in e83801f (#948), the commit that introduced both fields, and weren't mirrored to import_namespaces. This extends both branches to cover it and adds a round-trip test parametrized over the two fields.

Reproduced on 26.3:

>>> from packaging.metadata import Metadata, parse_email
>>> m = Metadata.from_raw({"metadata_version": "2.5", "name": "x", "version": "1", "import_namespaces": []}, validate=False)
>>> print(parse_email(m.as_rfc822().as_string())[0].get("import_namespaces"))
None
>>> # the same input with import_names gives []

import_names and import_namespaces (both Metadata 2.5 / PEP 794) share a
processor and are validated the same way, but only import_names special-cases
the empty-list value. As a result import_namespaces=[] is dropped on
as_rfc822() and parses back as None, and a bare Import-Namespace: header
raises on parse instead of yielding []. Both special cases were added for
import_names in e83801f (pypa#948) and weren't mirrored to import_namespaces.

Extend the parse ([""] -> []) and write ([] -> "") branches to cover
import_namespaces, and add a round-trip regression test parametrized over
both fields.
@henryiii

Copy link
Copy Markdown
Contributor

In PEP 794, Import-Name and Import-Namespaces are not symmetric.

The Import-Name and Import-Namespace fields are “multiple uses” fields. Each entry of both fields MUST be a valid import name or can be empty in the case of Import-Name.

Only Import-Name is allowed to be empty. This is to allow no import at all to be represented, but it must be represented as an empty Import-Name.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants