Skip to content

Commit d0adcdf

Browse files
authored
fix: __version__ guard catches everything and leaves it unset on failure (#206)
## Summary `spatialmath/__init__.py`'s `__version__` lookup used a bare `except: pass`, which has two problems: - Catches every exception during the `importlib.metadata.version()` call, not just the "package isn't installed" case (`PackageNotFoundError`) -- masking anything else that might go wrong there. - On failure, `__version__` never gets set at all -- `spatialmath.__version__` raises `AttributeError` rather than giving something to print, in e.g. a source checkout without an installed/editable distribution. Narrowed the `except` to `PackageNotFoundError` and added an explicit `"unknown"` fallback so the attribute always exists. ## Test plan - [x] Normal path: `import spatialmath; spatialmath.__version__` still resolves to the installed version (`1.1.16` locally) - [x] Failure path: monkeypatched `importlib.metadata.version` to raise `PackageNotFoundError` and confirmed `__version__` falls back to `"unknown"` instead of being unset - [x] New `tests/test_version.py`: asserts it's a non-empty string and matches `pyproject.toml`'s `version`
1 parent a016ffb commit d0adcdf

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

‎spatialmath/__init__.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,5 +51,8 @@
5151
import importlib.metadata
5252

5353
__version__ = importlib.metadata.version("spatialmath-python")
54-
except:
55-
pass
54+
except importlib.metadata.PackageNotFoundError:
55+
# running from a source checkout without an installed/editable
56+
# spatialmath-python distribution -- e.g. importing straight from
57+
# the repo root
58+
__version__ = "unknown"

‎tests/test_version.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import re
2+
import unittest
3+
from pathlib import Path
4+
5+
import spatialmath
6+
7+
8+
class TestVersion(unittest.TestCase):
9+
def test_version_is_a_non_empty_string(self):
10+
self.assertIsInstance(spatialmath.__version__, str)
11+
self.assertTrue(spatialmath.__version__)
12+
13+
def test_version_matches_pyproject(self):
14+
pyproject = Path(__file__).parent.parent / "pyproject.toml"
15+
match = re.search(r'^version\s*=\s*"([^"]+)"', pyproject.read_text(), re.MULTILINE)
16+
self.assertIsNotNone(match, f"couldn't find a version in {pyproject}")
17+
self.assertEqual(spatialmath.__version__, match.group(1))
18+
19+
20+
# ---------------------------------------------------------------------------------------#
21+
if __name__ == "__main__":
22+
unittest.main()

0 commit comments

Comments
 (0)