Accept `types.ModuleType` as a distribution identifier
I have recently ran into the issue where the importable module did not come from the distribution metadata found by importlib.metadata. This was because the distribution modules were shadowed in sys.path, which can happen often in test environments.
It would be nice if we could pass a module to importlib.metadata.distribution(), and have it find the distribution where that module originates from, if any.
Sounds reasonable. I'm yet unsure if distribution should be expanded to support more input types or if there should be a separate function specifically for ModuleType. We should consider the option of having a separate function, e.g.:
def distribution_for_module(module: ModuleType) -> Distribution`):
# search all of the distributions found in module.__path__ for a distribution whose files contains module.__file__
...
Assuming we choose to recycle the distribution function, it should utilize functools.singledispatch:
@singledispatch
def distribution(distribution_name: str | ModuleType, /) -> Distribution:
return Distribution.from_name(distribution_name)
@distribution.register
def _(distribution_name: ModuleType, /) -> Distribution:
return _distribution_for_module(distribution_name)
I think the implementation is going to be tricky, as there's not a definitive mapping from a module to the distribution that contains it, only an implicit one, and only if making assumptions about the loader.
I think we should start with a proposal for how the distribution_for_module would be implemented.