From 87060dfa51bc51e6ca995e9e3ed171619c283eca Mon Sep 17 00:00:00 2001 From: Jonas Lundholm Bertelsen Date: Sat, 1 Feb 2025 17:56:07 +0100 Subject: [PATCH] Use platformdirs for cpuinfo cache --- pyproject.toml | 1 + src/blosc2/core.py | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4be91feb..57d98fc3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,6 +37,7 @@ dependencies = [ "numexpr", "py-cpuinfo", "httpx", + "platformdirs", ] version = "3.0.1.dev" diff --git a/src/blosc2/core.py b/src/blosc2/core.py index 1bc9db7c..2ab86562 100644 --- a/src/blosc2/core.py +++ b/src/blosc2/core.py @@ -21,10 +21,11 @@ import sys from dataclasses import asdict from functools import lru_cache -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import cpuinfo import numpy as np +import platformdirs import blosc2 from blosc2 import blosc2_ext @@ -36,6 +37,12 @@ import torch +_USER_CACHE_DIR: pathlib.Path = platformdirs.user_cache_path( + appname="python-blosc2", + appauthor="blosc", +) + + def _check_typesize(typesize): if not 1 <= typesize <= blosc2_ext.MAX_TYPESIZE: raise ValueError(f"typesize can only be in the 1-{blosc2_ext.MAX_TYPESIZE} range.") @@ -1170,14 +1177,15 @@ def _get_cpu_info(): return cpu_info -def write_cached_cpu_info(cpu_info_dict: dict[str, any]) -> None: - with open(pathlib.Path.home() / ".blosc2-cpuinfo.json", "w") as f: +def write_cached_cpu_info(cpu_info_dict: dict[str, Any]) -> None: + _USER_CACHE_DIR.mkdir(parents=True, exist_ok=True) + with (_USER_CACHE_DIR / "cpuinfo.json").open("w") as f: json.dump(cpu_info_dict, f, indent=4) -def read_cached_cpu_info() -> dict: +def read_cached_cpu_info() -> dict[str, Any]: try: - with open(pathlib.Path.home() / ".blosc2-cpuinfo.json") as f: + with (_USER_CACHE_DIR / "cpuinfo.json").open() as f: return json.load(f) except (FileNotFoundError, json.JSONDecodeError): return {}