importlib_metadata icon indicating copy to clipboard operation
importlib_metadata copied to clipboard

Type hint for Distribution.metadata is incorrect

Open mpurnell1 opened this issue 10 months ago • 1 comments

I encountered this while trying to help sentry-python prepare for the changes mentioned in #371. Their linter errored with "PackageMetadata" has no attribute "get", since metadata is advertised to return _meta.PackageMetadata, but actually returns _adapters.Message.

Is this intended, and if so what is the workaroud for the linter?

Reproduction steps:

  1. git clone [email protected]:mpurnell1/sentry-python.git
  2. pip install tox
  3. tox -e linters

mpurnell1 avatar Feb 11 '25 14:02 mpurnell1

It seems the issue is not caused by metadata returning _adapters.Message. Workaround is below, but the typing should maybe still be updated.

... mypy is complaining about PackageMetadata having no .get. Like in most cases that have to do with mypy I'm not sure what's confusing since it isn't the case. Feel free to add a type: ignore[attr-defined] on the line to silence it.

Originally posted by @sentrivana in https://github.com/getsentry/sentry-python/issues/4039#issuecomment-2651134256

mpurnell1 avatar Feb 11 '25 15:02 mpurnell1

Note that PackageMetadata is a Protocol, which simply defines the interface that's expected for that type. _adapters.Message is the implementation that's expected to implement that protocol. Feel free to read up on protocols and typing systems or ask your colleagues for more details.

And as you can see from the spec, PackageMetadata does in fact implement get, so the problem is likely with the linter (mypy) or with sentry's use. It's also conceivable that you're working with a different, older version of importlib_metadata.

I don't believe there's any problem with importlib_metadata, but if there is, you'll need to dig deeper to characterize the problem in a more minimal reproducer (e.g. can you replicate the issue in a few lines using just mypy and importlib_metadata?).

jaraco avatar Apr 27 '25 12:04 jaraco