How to fix Python cache3 ImportError: cannot import name 'SafeCache' from 'cache3'

Problem:

You want to use cache3’s SafeCache as shown in the Quickstart

from cache3 import SafeCache
cache = SafeCache()

but you instead see the following error message:

ImportError: cannot import name 'SafeCache' from 'cache3' (/usr/local/lib/python3.10/dist-packages/cache3/__init__.py)

Solution

cache3 has been updated, but the documentation still has not been fixed. This is a known bug.

The closest equivalent is Cache() with thread_safe=True, an in-memory cache which supports tagging:

from cache3 import Cache
cache = Cache(name="mycache", thread_safe=True)

In case you don’t need tagging,  consider MiniCache:

from cache3 import MiniCache
cache = MiniCache(name="mycache", thread_safe=True)