Open
Description
class DeprecatedDict(dict):
def __init__(self, *args, **kwargs):
# Initialize with a standard dict, plus a set to track deprecated keys
super().__init__(*args, **kwargs)
self._deprecated_keys = set()
def mark_deprecated(self, key):
"""Mark a key as deprecated."""
if key in self:
self._deprecated_keys.add(key)
else:
print(f"Warning: Key '{key}' does not exist in the dictionary.")
def __getitem__(self, key):
# If the key is deprecated, print a warning
if key in self._deprecated_keys:
print(f"Warning: Accessing deprecated key '{key}'.")
# Return the actual value
return super().__getitem__(key)
def __delitem__(self, key):
# Remove key from deprecated set if it's deleted
self._deprecated_keys.discard(key)
super().__delitem__(key)
def is_deprecated(self, key):
"""Check if a key is marked as deprecated."""
return key in self._deprecated_keys
# Initialize and add some items
my_dict = DeprecatedDict(a=1, b=2, c=3)
# Mark key 'b' as deprecated
my_dict.mark_deprecated('b')
# Accessing the key 'b' will trigger a warning
print(my_dict['b']) # Output: Warning: Accessing deprecated key 'b'. \n 2
# Accessing non-deprecated key 'a' works normally
print(my_dict['a']) # Output: 1
# Deleting 'b' will also remove it from the deprecated set
del my_dict['b']