From 98ccab49f550b1cb0114cdb7f492b87618fa43cd Mon Sep 17 00:00:00 2001 From: Jeremy Stephens Date: Fri, 25 Sep 2026 16:53:13 -0700 Subject: [PATCH] Prefer _version.py over importlib.metadata at import time Try importing the build-time generated tabulate._version module first, and only import importlib.metadata as a fallback when _version.py is not present (e.g. in an unbuilt git checkout). Since pyproject.toml configures flit_scm / setuptools_scm with write_to = "tabulate/_version.py", standard wheels and sdists already include _version.py. Importing it directly avoids loading importlib.metadata (and its transitive zipfile, email, pathlib, and csv imports) and scanning sys.path for .dist-info directories on every import tabulate. --- tabulate/__init__.py | 12 +++++++----- test/test_api.py | 8 +++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 449f78c..90998a2 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -7,7 +7,6 @@ from decimal import Decimal from functools import partial, reduce from html import escape as htmlescape -from importlib.metadata import PackageNotFoundError, version import io from itertools import chain, zip_longest as izip_longest import math @@ -21,12 +20,15 @@ except ImportError: wcwidth = None + try: - __version__ = version("tabulate") # installed package -except PackageNotFoundError: + from ._version import version as __version__ # generated by flit_scm / setuptools_scm +except ImportError: + from importlib.metadata import PackageNotFoundError, version + try: - from ._version import version as __version__ # editable / source checkout - except ImportError: + __version__ = version("tabulate") + except PackageNotFoundError: __version__ = "unknown" diff --git a/test/test_api.py b/test/test_api.py index cb59836..d6ba280 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -1,6 +1,6 @@ """API properties.""" -from tabulate import simple_separated_format, tabulate, tabulate_formats +from tabulate import __version__, simple_separated_format, tabulate, tabulate_formats from common import skip @@ -11,6 +11,12 @@ _empty = None +def test_tabulate_version(): + "API: __version__ is a non-empty string" + assert type(__version__) is str + assert len(__version__) > 0 + + def test_tabulate_formats(): "API: tabulate_formats is a list of strings" supported = tabulate_formats