Skip to content

Instantly share code, notes, and snippets.

@expobrain
Created July 16, 2019 15:01
Show Gist options
  • Save expobrain/7f749a33168b5a475fca16c7d67ee46d to your computer and use it in GitHub Desktop.
Save expobrain/7f749a33168b5a475fca16c7d67ee46d to your computer and use it in GitHub Desktop.
Dict type which behaves like the Optional Chaining operator https://github.com/tc39/proposal-optional-chaining
class NoneDict:
def __truedive__(self, key):
return self
def __or__(self, key):
return self
def __repr__(self):
return "NoneDict"
class Dict2(dict):
def __truediv__(self, key):
v = self[key]
if isinstance(v, dict):
return Dict2(v)
return v
def __or__(self, key):
if key not in self:
return NoneDict()
v = self[key]
if isinstance(v, dict):
return Dict2(v)
return v
d = Dict2({"a": {"b": 2}})
print(d / "a")
print(d / "a" / "b")
print(d | "a")
print(d | "aa")
print(d | "aa" | "b")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment