Skip to content

Commit 8be3ae6

Browse files
Cache /etc/debian_version content (#349)
This patch is a follow-up for 6d44662 (#333), introducing caching of `/etc/debian_version` file content, to prevent opening and reading operations for each `distro.version()` call.
1 parent 095882f commit 8be3ae6

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

src/distro/distro.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -900,13 +900,7 @@ def version(self, pretty: bool = False, best: bool = False) -> str:
900900
versions.insert(0, self.oslevel_info())
901901
elif self.id() == "debian" or "debian" in self.like().split():
902902
# On Debian-like, add debian_version file content to candidates list.
903-
try:
904-
with open(
905-
os.path.join(self.etc_dir, "debian_version"), encoding="ascii"
906-
) as fp:
907-
versions.append(fp.readline().rstrip())
908-
except FileNotFoundError:
909-
pass
903+
versions.append(self._debian_version)
910904
version = ""
911905
if best:
912906
# This algorithm uses the last version in priority order that has
@@ -1217,6 +1211,16 @@ def _oslevel_info(self) -> str:
12171211
return ""
12181212
return self._to_str(stdout).strip()
12191213

1214+
@cached_property
1215+
def _debian_version(self) -> str:
1216+
try:
1217+
with open(
1218+
os.path.join(self.etc_dir, "debian_version"), encoding="ascii"
1219+
) as fp:
1220+
return fp.readline().rstrip()
1221+
except FileNotFoundError:
1222+
return ""
1223+
12201224
@staticmethod
12211225
def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]:
12221226
if not lines:

tests/test_distro.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2272,6 +2272,6 @@ def test_repr(self) -> None:
22722272
repr_str = repr(distro._distro)
22732273
assert "LinuxDistribution" in repr_str
22742274
for attr in MODULE_DISTRO.__dict__.keys():
2275-
if attr in ("root_dir", "etc_dir", "usr_lib_dir"):
2275+
if attr in ("root_dir", "etc_dir", "usr_lib_dir", "_debian_version"):
22762276
continue
22772277
assert f"{attr}=" in repr_str

0 commit comments

Comments
 (0)