Advertisement
phi2dao

SinfulDict

Jan 17th, 2025 (edited)
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. class NamedDict(dict[str, Any]):
  2.     class _Get:
  3.         __slots__ = ('instance',)
  4.         instance: 'NamedDict'
  5.  
  6.         def __call__(self, key: str, default=None):
  7.             return super(NamedDict, self.instance).get(key, default)
  8.  
  9.         def __get__(self, instance, owner=None):
  10.             self.instance = instance
  11.             return self
  12.  
  13.         def __getattr__(self, name: str):
  14.             return super(NamedDict, self.instance).get(name)
  15.  
  16.     class _SetDefault:
  17.         __slots__ = ('instance',)
  18.         instance: 'NamedDict'
  19.  
  20.         def __call__(self, key: str, default=None):
  21.             return super(NamedDict, self.instance).setdefault(key, default)
  22.  
  23.         def __get__(self, instance, owner=None):
  24.             self.instance = instance
  25.             return self
  26.  
  27.         def __getattr__(self, name: str):
  28.             def setdefault(default=None):
  29.                 return super(NamedDict, self.instance).setdefault(name, default)
  30.  
  31.             return setdefault
  32.  
  33.     get = _Get()
  34.     setdefault = _SetDefault()
  35.  
  36.     def __getattr__(self, name: str):
  37.         return self[name]
  38.  
  39.     def __setattr__(self, name: str, value):
  40.         if name in vars(self):
  41.             super().__setattr__(name, value)
  42.         else:
  43.             self[name] = value
  44.  
  45.     def __delattr__(self, name: str):
  46.         if name in vars(self):
  47.             super().__delattr__(name)
  48.         else:
  49.             del self[name]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement