Skip to content

Commit bf8b9e7

Browse files
authored
Fix _is_package_available to handle underscore/hyphen equivalence (#42615)
Fix minibug
1 parent 552409e commit bf8b9e7

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/transformers/utils/import_utils.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,15 @@ def _is_package_available(pkg_name: str, return_version: bool = False) -> tuple[
5555
# importlib.metadata works with the distribution package, which may be different from the import
5656
# name (e.g. `PIL` is the import name, but `pillow` is the distribution name)
5757
distributions = PACKAGE_DISTRIBUTION_MAPPING[pkg_name]
58-
# In most cases, the packages are well-behaved and both have the same name. If it's not the case, we
59-
# pick the first item of the list as best guess (it's almost always a list of length 1 anyway)
60-
distribution_name = pkg_name if pkg_name in distributions else distributions[0]
58+
# Per PEP 503, underscores and hyphens are equivalent in package names.
59+
# Prefer the distribution that matches the (normalized) package name.
60+
normalized_pkg_name = pkg_name.replace("_", "-")
61+
if normalized_pkg_name in distributions:
62+
distribution_name = normalized_pkg_name
63+
elif pkg_name in distributions:
64+
distribution_name = pkg_name
65+
else:
66+
distribution_name = distributions[0]
6167
package_version = importlib.metadata.version(distribution_name)
6268
except (importlib.metadata.PackageNotFoundError, KeyError):
6369
# If we cannot find the metadata (because of editable install for example), try to import directly.

0 commit comments

Comments
 (0)