Skip to content

Instantly share code, notes, and snippets.

@afonasev
Created June 14, 2018 10:42
Show Gist options
  • Save afonasev/02668b098cdb44ca989824bcc9f30f16 to your computer and use it in GitHub Desktop.
Save afonasev/02668b098cdb44ca989824bcc9f30f16 to your computer and use it in GitHub Desktop.
Optinal
class Optional:
"""
>>> class User:
... def __init__(self, friend_a, friend_b):
... self.friend_a = friend_a
... self.friend_b = friend_b
...
... def calc(self):
... return 5
...
>>> user_a = User(None, None)
>>> user_b = User(user_a, None)
>>> Optial(user_b).friend_a.calc().v
5
>>> Optial(user_b).friend_a.calc().v
None
>>> Optial(user_a).friend_b.v
None
"""
def __init__(self, value):
self.v = value
def __call__(self, *args, **kw):
if self.v is None:
return self.__class__(None)
return self.__class__(self.v(*args, **kw))
def __getattr__(self, item):
if self.v is None:
return self.__class__(None)
return self.__class__(getattr(self.v, item))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment