From b8ee74bd6361db6035856c875dfee2ad03c0372d Mon Sep 17 00:00:00 2001 From: Eric Prestat Date: Sat, 3 Feb 2024 11:22:03 +0000 Subject: [PATCH] Improve getting `__version__` --- hyperspy_gui_ipywidgets/__init__.py | 42 +++++++++++++++++++---------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/hyperspy_gui_ipywidgets/__init__.py b/hyperspy_gui_ipywidgets/__init__.py index b0ccaf4..e9303b1 100644 --- a/hyperspy_gui_ipywidgets/__init__.py +++ b/hyperspy_gui_ipywidgets/__init__.py @@ -18,19 +18,33 @@ import importlib +from importlib.metadata import version from pathlib import Path -if Path(__file__).parent.parent.name == "site-packages": # pragma: no cover - # Tested in the "Package & Test" workflow on GitHub CI - from importlib.metadata import version +__version__ = version("rosettasciio") - __version__ = version("hyperspy_gui_ipywidgets") -else: - # Editable install - from setuptools_scm import get_version +# For development version, `setuptools_scm` will be used at build time +# to get the dev version, in case of missing vcs information (git archive, +# shallow repository), the fallback version defined in pyproject.toml will +# be used - __version__ = get_version(Path(__file__).parent.parent) +# if we have a editable install from a git repository try to use +# `setuptools_scm` to find a more accurate version: +# `importlib.metadata` will provide the version at installation +# time and for editable version this may be different + +# we only do that if we have enough git history, e.g. not shallow checkout +_root = Path(__file__).resolve().parents[1] +if (_root / ".git").exists() and not (_root / ".git/shallow").exists(): + try: + # setuptools_scm may not be installed + from setuptools_scm import get_version + + __version__ = get_version(_root) + except ImportError: # pragma: no cover + # setuptools_scm not install, we keep the existing __version__ + pass __all__ = [ @@ -49,11 +63,11 @@ def __dir__(): def __getattr__(name): + # lazy loading of module: this is only call when the attribute "name" is not found + # in the module + # See https://peps.python.org/pep-0562/ if name in __all__: - if name == "__version__": - return __version__ - else: - return importlib.import_module( - "." + name, 'hyperspy_gui_ipywidgets' - ) + return importlib.import_module( + "." + name, 'hyperspy_gui_ipywidgets' + ) raise AttributeError(f"module {__name__!r} has no attribute {name!r}")