Advertisement
HasteBin0

Python 3.10+ Two Function Complete Monad Library!

Sep 17th, 2023
1,218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | Software | 0 0
  1. # py_struct = NamedTuple
  2. class CompareResult(py_struct):
  3.     les: bool
  4.     equ: bool
  5.     gtr: bool
  6.  
  7.  
  8. cmp_str_input_t = NewType('cmp_str_input_t', Iterable[SupportsBytes and SupportsIndex and SupportsInt])
  9.  
  10.  
  11. def cmp_iter_str(si1: cmp_str_input_t, si2: cmp_str_input_t) -> CompareResult:
  12.     it1 = iter(si1)
  13.     it2 = iter(si2)
  14.     while True:
  15.         c1 = next(it1, None)
  16.         c2 = next(it2, None)
  17.         n1 = c1 is None
  18.         n2 = c2 is None
  19.         if n1 and n2:
  20.             return CompareResult(False, True, False)
  21.         elif n1 ^ n2:
  22.             return CompareResult(n1, False, n2)
  23.         elif c1 != c2:
  24.             return CompareResult(c1 < c2, False, c1 > c2)
  25.  
  26.  
  27. class monad_attr_err_spec_t(py_struct):
  28.     obj_type: Type[Any]
  29.     attr_name: str
  30.     fxn_triggered: callable
  31.  
  32.  
  33. def monad(call_function: callable, *op_types: monad_attr_err_spec_t, pass_types: bool = False) -> callable:
  34.     def _i(*args, **kwargs):
  35.         try:
  36.             if pass_types:
  37.                 return call_function(*args, op_types = op_types, **kwargs)
  38.             return call_function(*args, **kwargs)
  39.         except AttributeError as attr_err:  # https://docs.python.org/3.11/library/exceptions.html#AttributeError
  40.             if attr_err.obj is None:
  41.                 return
  42.             ae_obj, ae_name = attr_err.obj, attr_err.name  # Changed in version 3.10: Added the name and obj attributes.
  43.             x: monad_attr_err_spec_t
  44.             for x in op_types:
  45.                 if x.obj_type is type(ae_obj) and ae_name == x.attr_name:
  46.                     return x.fxn_triggered(*args, ae_obj = ae_obj, ae_name = ae_name, **kwargs)
  47.    
  48.     return _i
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement