Use functools.cache instead of manual global cache

Replaces the hand-rolled '_cached_value' module global with @functools.cache, which is the standard Python idiom for memoization. Tests now use the built-in get_deploy_environment.cache_clear() to reset between cases.

Amp-Thread-ID: https://ampcode.com/threads/T-019df26e-96f4-7518-94da-0e4263680e3c
Co-authored-by: Amp <amp@ampcode.com>
This commit is contained in:
Jedrzej Kosinski 2026-05-04 06:55:54 -07:00
parent 06e416bd0d
commit 22186b3dae
2 changed files with 7 additions and 14 deletions

View File

@ -1,3 +1,4 @@
import functools
import logging
import os
@ -8,14 +9,9 @@ logger = logging.getLogger(__name__)
_DEFAULT_DEPLOY_ENV = "local_git"
_ENV_FILENAME = ".comfy_environment"
_cached_value: str | None = None
@functools.cache
def get_deploy_environment() -> str:
global _cached_value
if _cached_value is not None:
return _cached_value
env_file = os.path.join(folder_paths.base_path, _ENV_FILENAME)
try:
with open(env_file, encoding="utf-8") as f:
@ -24,12 +20,10 @@ def get_deploy_environment() -> str:
first_line = f.readline(128).strip()
value = "".join(c for c in first_line if 32 <= ord(c) < 127)
if value:
_cached_value = value
return _cached_value
return value
except FileNotFoundError:
pass
except Exception as e:
logger.error("Failed to read %s: %s", env_file, e)
_cached_value = _DEFAULT_DEPLOY_ENV
return _cached_value
return _DEFAULT_DEPLOY_ENV

View File

@ -4,18 +4,17 @@ import os
import pytest
from comfy import deploy_environment
from comfy.deploy_environment import get_deploy_environment
@pytest.fixture(autouse=True)
def _reset_cache_and_base_path(tmp_path, monkeypatch):
"""Reset the module cache and point folder_paths.base_path at a tmp dir for each test."""
monkeypatch.setattr(deploy_environment, "_cached_value", None)
"""Reset the functools cache and point folder_paths.base_path at a tmp dir for each test."""
get_deploy_environment.cache_clear()
import folder_paths
monkeypatch.setattr(folder_paths, "base_path", str(tmp_path))
yield
monkeypatch.setattr(deploy_environment, "_cached_value", None)
get_deploy_environment.cache_clear()
def _write_env_file(tmp_path, content: str) -> str: