close
Skip to content

Allow importlib_metadata.distributions() to enumerate distributions under a given path #85

Description

@jaraco

In GitLab by @yan12125 on Sep 6, 2019, 08:27

I'm working on porting a script from pkg_resources to importlib_metadata. A missing feature is that I cannot enumerate distributions under a given path easily.

With pkg_resources, I do this:

for dist in pkg_resources.WorkingSet([some_path]):
    analyze_disttribution(dist)

importlib_metadata.distributions() appears to be the replacement. However, I need to manipulate sys.path manually:

orig_sys_path = sys.path
sys.path = [some_path]
for dist in importlib_metadata.distributions():
    analyze_disttribution(dist)
sys.path = orig_sys_path

Could you consider adding a parameter to importlib_metadata.distributions()? Here is a proof-of-concept patch:

diff --git a/importlib_metadata/__init__.py b/importlib_metadata/__init__.py
index 2583c3f..cf535bc 100644
--- a/importlib_metadata/__init__.py
+++ b/importlib_metadata/__init__.py
@@ -184,13 +184,13 @@ class Distribution:
             raise PackageNotFoundError(name)
 
     @classmethod
-    def discover(cls):
+    def discover(cls, path=None):
         """Return an iterable of Distribution objects for all packages.
 
         :return: Iterable of Distribution objects for all packages.
         """
         return itertools.chain.from_iterable(
-            resolver()
+            resolver(path=path)
             for resolver in cls._discover_resolvers()
             )
 
@@ -430,12 +430,12 @@ def distribution(package):
     return Distribution.from_name(package)
 
 
-def distributions():
+def distributions(path=None):
     """Get all ``Distribution`` instances in the current environment.
 
     :return: An iterable of ``Distribution`` instances.
     """
-    return Distribution.discover()
+    return Distribution.discover(path)
 
 
 def metadata(package):

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions