Skip to content

Commit

Permalink
Add casts for package metadata
Browse files Browse the repository at this point in the history
In the latest mypy (0.942), importlib.metadata.metadata now returns
a Protocol named PackageMetadata that doesn't implement the get
method.  The actual object remains a Message class, however, so the
get method works correctly.  Only mypy checking fails.

Pending python/typeshed#7767, which may
reveal that it is intentional that get not be supported, cast the
return value to Message so that the existing functions work.  This
seems better than adding try/catch blocks for every piece of
metadata of interest given that the omission of get appears to be
unintentional.
  • Loading branch information
rra committed May 2, 2022
1 parent 8930749 commit 3612e45
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/safir/metadata.py
Expand Up @@ -5,7 +5,7 @@

from email.message import Message
from importlib.metadata import metadata
from typing import Optional
from typing import Optional, cast

from pydantic import BaseModel, Field

Expand Down Expand Up @@ -66,7 +66,7 @@ def get_metadata(*, package_name: str, application_name: str) -> Metadata:
project_urls, Source code
Used as the ``respository_url``.
"""
pkg_metadata: Message = metadata(package_name)
pkg_metadata: Message = cast(Message, metadata(package_name))
return Metadata(
name=application_name,
version=pkg_metadata.get("Version", "0.0.0"),
Expand Down
8 changes: 3 additions & 5 deletions tests/metadata_test.py
Expand Up @@ -3,20 +3,18 @@

from __future__ import annotations

from email.message import Message
from importlib.metadata import metadata
from typing import TYPE_CHECKING
from typing import cast

import pytest

from safir.metadata import get_metadata, get_project_url

if TYPE_CHECKING:
from email.message import Message


@pytest.fixture(scope="session")
def safir_metadata() -> Message:
return metadata("safir")
return cast(Message, metadata("safir"))


def test_get_project_url(safir_metadata: Message) -> None:
Expand Down

0 comments on commit 3612e45

Please sign in to comment.