Opened 7 years ago

Closed 7 years ago

Last modified 4 years ago

#7967 closed (fixed)

cache.has_key() doesn't do the same thing as "key in cache"

Reported by: Gulopine Owned by: Gulopine
Component: Core (Other) Version: master
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


In [source:django/trunk/django/core/cache/backends/ django.core.cache.backends.base.BaseCache], has_key() is defined as a method, while __contains__ is simply an alias for it. Individual backends override has_key() to be more efficient, but __contains__ is left alone, so it's still an alias for the base function, which unfortunately means that the two end up with different implementations. This is generally fine, but shows itself when None is stored in the cache, which is a potentially useful situation.

>>> from django.core.cache import cache
>>> cache.set('test', None)
>>> cache.has_key('test')
>>> 'test' in cache

Attachments (1)

7967-r8075.diff (1.5 KB) - added by Gulopine 7 years ago.
Fixed __contains__ to always call has_key() and added tests to verify they work the same way.

Download all attachments as: .zip

Change History (4)

Changed 7 years ago by Gulopine

Fixed __contains__ to always call has_key() and added tests to verify they work the same way.

comment:1 Changed 7 years ago by Gulopine

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

For what it's worth, I tested with with locmem, but since key in cache always calls BaseCache.__contains__, it actually doesn't matter what backend is used. There's also probably a case to be made that BaseCache.has_key() itself is buggy, since it could specify a default instead of assuming the default will always be None, but since all the backends override it, it's not a concern unless a custom backend (which is only recently possible) doesn't supply its own has_key().

comment:2 Changed 7 years ago by mtredinnick

  • Resolution set to fixed
  • Status changed from new to closed

(In [8084]) Fixed #7967 -- Make sure the contains method in the cache backends call the
right has_key() method for the subclass. Patch from Marty Alchin.

comment:3 Changed 4 years ago by jacob

  • milestone 1.0 deleted

Milestone 1.0 deleted

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