Skip to content

Accept types.ModuleType as a distribution identifier #511

Description

@FFY00

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.

Activity

  1. jaraco commented on Apr 27, 2025

    @jaraco
    Member

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions