Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

provide deprecated key access mechanism #200

Open
mwfarb opened this issue Oct 25, 2024 · 0 comments
Open

provide deprecated key access mechanism #200

mwfarb opened this issue Oct 25, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@mwfarb
Copy link
Contributor

mwfarb commented Oct 25, 2024

@hi-liang

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']
@mwfarb mwfarb added the enhancement New feature or request label Oct 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant