Opened 11 years ago

Closed 11 years ago

#20315 closed Cleanup/optimization (invalid)

Default cache instance is memoized, but no other cache instance is

Reported by: acjohnson55 Owned by: nobody
Component: Core (Cache system) Version: 1.5
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

It seems odd to me that the default cache instance is stored forever at module load-time, but that any cache instance retrieved by get_cache is recreated every time. Is there a reason get_cache is not memoized but the default cache is? I ask because I'm working on a library that rides on top of the caching library, and I'm trying to make sure there's no danger in memoizing cache instances, as django.core.cache.cache is. If the cache object is expensive to create, this could really make a difference.

From django/core/cache/init.py:

def get_cache(backend, **kwargs):
    try:
        if '://' in backend:
            # for backwards compatibility
            backend, location, params = parse_backend_uri(backend)
            if backend in BACKENDS:
                backend = 'django.core.cache.backends.%s' % BACKENDS[backend]
            params.update(kwargs)
            mod = importlib.import_module(backend)
            backend_cls = mod.CacheClass
        else:
            backend, location, params = parse_backend_conf(backend, **kwargs)
            backend_cls = import_by_path(backend)
    except (AttributeError, ImportError, ImproperlyConfigured) as e:
        raise InvalidCacheBackendError(
            "Could not find backend '%s': %s" % (backend, e))
    cache = backend_cls(location, params)
    # Some caches -- python-memcached in particular -- need to do a cleanup at the
    # end of a request cycle. If not implemented in a particular backend
    # cache.close is a no-op
    signals.request_finished.connect(cache.close)
    return cache

cache = get_cache(DEFAULT_CACHE_ALIAS)

Change History (1)

comment:1 by Aymeric Augustin, 11 years ago

Resolution: invalid
Status: newclosed

The definition of cache is purely provided for (a) convenience (b) backwards-compatibility with versions of Django that didn't support multiple caches.

Note: See TracTickets for help on using tickets.
Back to Top