Forum Archive

Pythonistas cache memory

KiloPasztetowej

Hello there.
Is there something like cache memory in Pythonista? Functions inside editor module are very useful and will allow for vim-like extension for Pythonista, but such extension would need to register some data in between keystrokes/script runs since commands are chained.
Does something like that exist in Pythonista? Or do I have to use some hacks like storing this data in some files or something else? I’d really like to avoid messing with clipboard too.

mikael

@KiloPasztetowej, some different options, including using Apple reminders, but I think the most straightforward approach is to just put a file in a unix standard temp directory:

import json
from pathlib import Path
from tempfile import gettempdir

cache_name = 'vim.cache'
cache_file = Path(gettempdir()) / cache_name

def cache_put(data):
    with cache_file.open('w') as fp:
        json.dump(data, fp)

def cache_get():
    if not cache_file.exists():
        return None
    with cache_file.open() as fp:
        return json.load(fp)

def cache_clear():
    if cache_file.exists():
        cache_file.unlink()

For your use case, you might want to include a time stamp and ignore/clear the cache if it is too old.

ccc

LRU Cache in https://docs.python.org/3/library/functools.html#functools.lru_cache

mikael

@ccc, I do not think lru_cache persists over script invocations, even in Pythonista.