From b5aef103da4319d20008c0e4eeaae83259328a44 Mon Sep 17 00:00:00 2001 From: Samuel FORESTIER Date: Mon, 10 Oct 2022 11:14:44 +0200 Subject: [PATCH] Cache `/etc/debian_version` content This patch is a follow-up for 6d44662, introducing caching of `/etc/debian_version` file content, to prevent opening and reading operations for each `distro.version()` call. --- src/distro/distro.py | 18 +++++++++++------- tests/test_distro.py | 2 +- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/distro/distro.py b/src/distro/distro.py index 8fc5a41..489b8ec 100755 --- a/src/distro/distro.py +++ b/src/distro/distro.py @@ -900,13 +900,7 @@ def version(self, pretty: bool = False, best: bool = False) -> str: versions.insert(0, self.oslevel_info()) elif self.id() == "debian" or "debian" in self.like().split(): # On Debian-like, add debian_version file content to candidates list. - try: - with open( - os.path.join(self.etc_dir, "debian_version"), encoding="ascii" - ) as fp: - versions.append(fp.readline().rstrip()) - except FileNotFoundError: - pass + versions.append(self._debian_version) version = "" if best: # This algorithm uses the last version in priority order that has @@ -1217,6 +1211,16 @@ def _oslevel_info(self) -> str: return "" return self._to_str(stdout).strip() + @cached_property + def _debian_version(self) -> str: + try: + with open( + os.path.join(self.etc_dir, "debian_version"), encoding="ascii" + ) as fp: + return fp.readline().rstrip() + except FileNotFoundError: + return "" + @staticmethod def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]: if not lines: diff --git a/tests/test_distro.py b/tests/test_distro.py index 36061d8..3dda970 100644 --- a/tests/test_distro.py +++ b/tests/test_distro.py @@ -2272,6 +2272,6 @@ def test_repr(self) -> None: repr_str = repr(distro._distro) assert "LinuxDistribution" in repr_str for attr in MODULE_DISTRO.__dict__.keys(): - if attr in ("root_dir", "etc_dir", "usr_lib_dir"): + if attr in ("root_dir", "etc_dir", "usr_lib_dir", "_debian_version"): continue assert f"{attr}=" in repr_str