Skip to content

Instantly share code, notes, and snippets.

@luzfcb
Last active October 7, 2022 00:31
Show Gist options
  • Save luzfcb/879b42974fb8a2005794e24ba53efd49 to your computer and use it in GitHub Desktop.
Save luzfcb/879b42974fb8a2005794e24ba53efd49 to your computer and use it in GitHub Desktop.
Invalidate cached_property
from functools import cached_property as functools_cached_property
try:
from django.utils.functional import cached_property as django_cached_property
except ImportError:
cached_property_classes = (
functools_cached_property,
)
else:
cached_property_classes = (
functools_cached_property,
django_cached_property,
)
def invalidate_cached_properties(obj):
"""
Invalidate all cached_property of an object.
Note: Does not work inside classes passing self as an argument
"""
if obj and hasattr(obj, '__class__'):
for key, value in obj.__class__.__dict__.items():
if isinstance(value, cached_property_classes):
value = obj.__dict__.pop(key, None)
try:
if value:
del value
except Exception: # noqa
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment