Created
July 16, 2019 15:01
-
-
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
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 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