Advertisement
Guest User

option_like_monad.py

a guest
Mar 29th, 2021
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. class M:
  2.     def __init__(self, val=None, exc=None):
  3.         self.val = val
  4.         self.exc = exc
  5.  
  6.     def __getattr__(self, item):
  7.         if self.exc:
  8.             return M(exc=self.exc)
  9.         if hasattr(self.val, item):
  10.             return M(getattr(self.val, item), self.exc)
  11.         raise Exception(f'missed attr {item}')
  12.  
  13.     def __call__(self, *args, **kwargs):
  14.         try:
  15.             return M(exc=self.exc) if self.exc\
  16.                 else M(val=self.val(*args, **kwargs))
  17.         except Exception as err:
  18.             return M(exc=err)
  19.  
  20.     def unwrap(self):
  21.         if self.exc:
  22.             raise self.exc
  23.         return self.val
  24.  
  25.  
  26. class TheA:
  27.     def a(self):
  28.         return TheB()
  29.  
  30.  
  31. class TheB:
  32.     def b(self, raise_exception):
  33.         if raise_exception:
  34.             raise Exception('Something went wrong')
  35.         return TheC()
  36.  
  37.  
  38. class TheC:
  39.     def c(self):
  40.         return 42
  41.  
  42. a = M(TheA()).a
  43. x = a().b(raise_exception=False).c().unwrap()
  44. print(x)
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement