python / importlib_metadata

Library to access metadata for Python packages
https://importlib-metadata.readthedocs.io
Apache License 2.0
122 stars 79 forks source link

add .get() to the PackageMetadata protocol #444

Closed dimbleby closed 1 year ago

dimbleby commented 1 year ago

__getitem__ warns that it will raise KeyError rather than returning None (I see #371 etc)

that's all very well but there's currently no comfortable way for users who anticipate missing values to write their code in a way that doesn't trigger that warning. We seem to be steered towards

import warnings
try:
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", "Implicit None .* KeyError", DeprecationWarning)
        value = metadata[key]
except KeyError:
    value = None

which sure seems like a lot of ceremony.

The natural way to do it would be just value = metadata.get(key). That method exists, but is not exposed by the protocol so if we try to use it then mypy shouts at us

Therefore add get() to that protocol (and testcases showing that it works).

dimbleby commented 1 year ago

Just spotted previous discussion in #384. Conversation there doesn't sound too opposed to this.

IMO it's a very natural thing to have on the API, perhaps the new annoyance with the hard-to-avoid warning, alongside an actual merge request, is enough to settle the matter...