From e1248ef3265a8c9d2e7de4e5995f66ab58747298 Mon Sep 17 00:00:00 2001 From: Abi Ullattil Date: Tue, 8 Apr 2025 19:40:56 +0000 Subject: [PATCH] Fixed the bug where pdl.__version__ was not set It wasn't set previously because importlib searches for the distribution name and not the module's top-level name. Fallbacks are in place to revert to searching for 'pdl', and if that fails, it fallsback to the hardcoded version in _version.py Signed-off-by: Abi Ullattil --- src/pdl/__init__.py | 33 +++++++++++++++++++++++++++++---- tests/test_lib_version.py | 16 ++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) create mode 100644 tests/test_lib_version.py diff --git a/src/pdl/__init__.py b/src/pdl/__init__.py index b43d1370b..a8b5ebc4a 100644 --- a/src/pdl/__init__.py +++ b/src/pdl/__init__.py @@ -1,6 +1,31 @@ from importlib.metadata import PackageNotFoundError, version -try: - __version__ = version("pdl") -except PackageNotFoundError: - pass +from ._version import __version__ as hardcoded_version + + +def _get_distribution_version(distribution_name: str) -> str: + """ + This function attempts to retrieve the version of PDL package using + importlib.metadata. + + When the package is not installed, importlib will raise a PackageNotFoundError. + In this case, we fallback to the hardcoded version. + + When the package is installed, but the distribution name does not match, + importlib will return the version of the package that is installed. + """ + try: + return version(distribution_name) + except PackageNotFoundError: + # This is a fallback for when the package is not recognized by importlib.metadata. + # This can happen when the package is not installed. + return ( + hardcoded_version + if distribution_name == "pdl" + else _get_distribution_version( + "pdl" # This is a fallback to maintain the previous behavior. + ) + ) + + +__version__ = _get_distribution_version("prompt-declaration-language") diff --git a/tests/test_lib_version.py b/tests/test_lib_version.py new file mode 100644 index 000000000..6969873e6 --- /dev/null +++ b/tests/test_lib_version.py @@ -0,0 +1,16 @@ +import pytest + +import pdl + + +def test_version(): + # Make sure the __version__ attribute is available. + assert pdl.__version__ is not None + + # Since pdl is not installed, the version returned will be the dev version. + # NOTE: For some reason, the version is not the same as the hardcoded version. + assert pdl.__version__.startswith("0.1.dev") + + +if __name__ == "__main__": + pytest.main(["-v", "--tb=short", __file__])