Skip to content

Instantly share code, notes, and snippets.

@B1Z0N
Created August 9, 2021 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save B1Z0N/bc671050436cabfda31a69da5a851175 to your computer and use it in GitHub Desktop.
Save B1Z0N/bc671050436cabfda31a69da5a851175 to your computer and use it in GitHub Desktop.
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class NoneDict(dict, metaclass=Singleton):
def __getitem__(self, key):
return NoneDict()
class NoneSubsDict(dict):
def __getitem__(self, key):
if (val := self.get(key)) is not None:
return NoneSubsDict(val) if isinstance(val, dict) else val
return NoneDict()
dct = NoneSubsDict({ 'a' : { 'b' : { 'c' : 'd' }}})
dct['a']['b']['c'] # 'd'
dct['a']['b']['5'] # NoneDict
dct['a']['5']['c'] # NoneDict
dct['5']['b']['c'] # NoneDict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment