Created
March 4, 2020 18:56
-
-
Save saml/f50fe931e82af33885f2f6665beba115 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
""" | |
# / is field access. | |
# .get() is unwrapping value. | |
# Invalid field access is ignored and returns None. | |
>>> (Wrap(1) / 'a' / 0 / 'b').get() | |
# You may specify default value in case invalid field was accessed. | |
>>> (Wrap(1) / 'a' / 0 / 'b').get(True) | |
True | |
>>> (Wrap([1, 2, {'fields': {'body': [{'fields': {'a': 'hello'}}]}}]) / 2 / 'fields' / 'body' / 0 / 'fields' / 'a').get() | |
'hello' | |
""" | |
class UnitWrap: | |
def __truediv__(self, other): | |
return self | |
def get(self, default=None): | |
return default | |
class Wrap: | |
def __init__(self, x): | |
self._x = x | |
def __truediv__(self, other): | |
try: | |
return Wrap(self._x[other]) | |
except (KeyError, TypeError, IndexError): | |
return UnitWrap() | |
def get(self, default=None): | |
return self._x | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment