From 06b8e268e284df02f9a6ffd6dbc2d3560e7a9ece Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Mon, 16 Sep 2019 16:46:47 +0200 Subject: [PATCH] Add compatibility shim to prevent exception on select Python versions. Closes #86. --- importlib_metadata/__init__.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/importlib_metadata/__init__.py b/importlib_metadata/__init__.py index ddd25797..f0e7eba8 100644 --- a/importlib_metadata/__init__.py +++ b/importlib_metadata/__init__.py @@ -178,7 +178,8 @@ def from_name(cls, name): metadata cannot be found. """ for resolver in cls._discover_resolvers(): - dists = resolver(DistributionFinder.Context(name=name)) + context = DistributionFinder.Context(name=name) + dists = cls._maybe_bind(resolver, context) dist = next(dists, None) if dist is not None: return dist @@ -200,10 +201,24 @@ def discover(cls, **kwargs): raise ValueError("cannot accept context and kwargs") context = context or DistributionFinder.Context(**kwargs) return itertools.chain.from_iterable( - resolver(context) + cls._maybe_bind(resolver, context) for resolver in cls._discover_resolvers() ) + @staticmethod + def _maybe_bind(resolver, context): + """ + Only bind the context to the resolver if as a callable, + the resolver accepts the context parameter. + + Workaround for + https://gitlab.com/python-devs/importlib_metadata/issues/86 + """ + try: # pragma: nocover + return resolver(context) + except TypeError: # pragma: nocover + return resolver(name=context.name, path=context.path) + @staticmethod def at(path): """Return a Distribution for the indicated metadata path