entry_points.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import annotations
  18. import functools
  19. import logging
  20. import sys
  21. from collections import defaultdict
  22. from typing import Iterator, Tuple
  23. if sys.version_info >= (3, 12):
  24. from importlib import metadata
  25. else:
  26. import importlib_metadata as metadata # type: ignore[no-redef]
  27. log = logging.getLogger(__name__)
  28. EPnD = Tuple[metadata.EntryPoint, metadata.Distribution]
  29. @functools.lru_cache(maxsize=None)
  30. def _get_grouped_entry_points() -> dict[str, list[EPnD]]:
  31. mapping: dict[str, list[EPnD]] = defaultdict(list)
  32. for dist in metadata.distributions():
  33. try:
  34. for e in dist.entry_points:
  35. mapping[e.group].append((e, dist))
  36. except Exception as e:
  37. log.warning("Error when retrieving package metadata (skipping it): %s, %s", dist, e)
  38. return mapping
  39. def entry_points_with_dist(group: str) -> Iterator[EPnD]:
  40. """
  41. Retrieve entry points of the given group.
  42. This is like the ``entry_points()`` function from ``importlib.metadata``,
  43. except it also returns the distribution the entry point was loaded from.
  44. Note that this may return multiple distributions to the same package if they
  45. are loaded from different ``sys.path`` entries. The caller site should
  46. implement appropriate deduplication logic if needed.
  47. :param group: Filter results to only this entrypoint group
  48. :return: Generator of (EntryPoint, Distribution) objects for the specified groups
  49. """
  50. return iter(_get_grouped_entry_points()[group])