Created
August 9, 2021 21:56
-
-
Save B1Z0N/bc671050436cabfda31a69da5a851175 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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