diff --git a/packages/google-api-core/google/api_core/_python_version_support.py b/packages/google-api-core/google/api_core/_python_version_support.py index 3a85f793a04b..66782bfc9ea8 100644 --- a/packages/google-api-core/google/api_core/_python_version_support.py +++ b/packages/google-api-core/google/api_core/_python_version_support.py @@ -16,6 +16,7 @@ import datetime import enum +import functools import logging import warnings import sys @@ -152,15 +153,16 @@ def _get_pypi_package_name(module_name): # pragma: NO COVER else: from importlib import metadata + @functools.cache + def _cached_packages_distributions(): + return metadata.packages_distributions() + def _get_pypi_package_name(module_name): """Determine the PyPI package name for a given module name.""" try: - # Get the mapping of modules to distributions - module_to_distributions = metadata.packages_distributions() + module_to_distributions = _cached_packages_distributions() - # Check if the module is found in the mapping if module_name in module_to_distributions: # pragma: NO COVER - # The value is a list of distribution names, take the first one return module_to_distributions[module_name][0] except Exception as e: # pragma: NO COVER _LOGGER.info( @@ -195,7 +197,6 @@ def check_python_version( The support status of the current Python version. """ today = today or datetime.date.today() - package_label, _ = _get_distribution_and_import_packages(package) python_version = sys.version_info version_tuple = (python_version.major, python_version.minor) @@ -221,7 +222,14 @@ def min_python(date: datetime.date) -> str: return f"{version[0]}.{version[1]}" return "at a currently supported version [https://devguide.python.org/versions]" + # Resolve the pretty package label lazily so we avoid any work on + # the happy path (supported Python version, no warning needed). + def get_package_label(): + label, _ = _get_distribution_and_import_packages(package) + return label + if gapic_end < today: + package_label = get_package_label() message = _flatten_message( f""" You are using a non-supported Python version ({py_version_str}). @@ -236,6 +244,7 @@ def min_python(date: datetime.date) -> str: eol_date = version_info.python_eol + EOL_GRACE_PERIOD if eol_date <= today <= gapic_end: + package_label = get_package_label() message = _flatten_message( f""" You are using a Python version ({py_version_str}) @@ -250,6 +259,7 @@ def min_python(date: datetime.date) -> str: return PythonVersionStatus.PYTHON_VERSION_EOL if gapic_deprecation <= today <= gapic_end: + package_label = get_package_label() message = _flatten_message( f""" You are using a Python version ({py_version_str}) which Google will