From 87e5ed54257cd4a04d4f2cdb0f6512b32247e6b8 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Mon, 17 Aug 2026 17:28:44 +1000 Subject: [PATCH] fix: __version__ guard catches everything and leaves it unset on failure Bare except: pass means any exception during the importlib.metadata lookup gets silently swallowed (not just PackageNotFoundError for "not installed"), and __version__ never gets set at all in that case -- spatialmath.__version__ raises AttributeError instead of giving something to print. Narrow the except to PackageNotFoundError and fall back to an explicit "unknown" so the attribute always exists. --- spatialmath/__init__.py | 7 +++++-- tests/test_version.py | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 tests/test_version.py diff --git a/spatialmath/__init__.py b/spatialmath/__init__.py index 551481e1..97922905 100644 --- a/spatialmath/__init__.py +++ b/spatialmath/__init__.py @@ -51,5 +51,8 @@ import importlib.metadata __version__ = importlib.metadata.version("spatialmath-python") -except: - pass +except importlib.metadata.PackageNotFoundError: + # running from a source checkout without an installed/editable + # spatialmath-python distribution -- e.g. importing straight from + # the repo root + __version__ = "unknown" diff --git a/tests/test_version.py b/tests/test_version.py new file mode 100644 index 00000000..e8590bb6 --- /dev/null +++ b/tests/test_version.py @@ -0,0 +1,22 @@ +import re +import unittest +from pathlib import Path + +import spatialmath + + +class TestVersion(unittest.TestCase): + def test_version_is_a_non_empty_string(self): + self.assertIsInstance(spatialmath.__version__, str) + self.assertTrue(spatialmath.__version__) + + def test_version_matches_pyproject(self): + pyproject = Path(__file__).parent.parent / "pyproject.toml" + match = re.search(r'^version\s*=\s*"([^"]+)"', pyproject.read_text(), re.MULTILINE) + self.assertIsNotNone(match, f"couldn't find a version in {pyproject}") + self.assertEqual(spatialmath.__version__, match.group(1)) + + +# ---------------------------------------------------------------------------------------# +if __name__ == "__main__": + unittest.main()