Aug 27, 2016

[python] monad constructor


  def apply_func(monad):
      return monad.result

  def monad_constructor(f):
      """
      type constructor
      1. log
      2. build monad type
      """
      LOG = "Function: {func_name}, Status: {status}, Message: {message}"
      APPLY_FUNC = apply_func
      message = "testing message."

      @functools.wraps(f)
      def wrap(*args, **kargs):
          try:
              result = f(*args, **kargs)
              if result:
                  wrap.result = result
                  wrap.success = True
                  wrap.status = "OK."
              else:
                  wrap.result = None
                  wrap.success = False
                  wrap.status = "Failed."
          except Exception as e:
              wrap.result = str(e)
              wrap.success = False
              wrap.status = "Failed."
          finally:
              wrap.apply = APPLY_FUNC
              wrap.log_msg = LOG.format(
                  func_name=f.__name__,
                  status=wrap.status,
                  message=message)
      return wrap

@monad_constructor
  def none_func():
      """None function
      :return: bool
      """
      return True

@monad_constructor
  def set_log(monad):
      """Setup log
      :param monad: function as monad
      :return: bool
      """
      raise Exception("set log failed")

@monad_constructor
  def access_xen(monad):
      return auth_info


@monad_constructor
  def check_xen_status(monad):
      xen_auth = monad.apply(monad)
      #...
      

def main():
    none_func()
    set_log(none_func)
    access_xen(set_log)
    check_xen_status(access_xen)


if __name__ == "__main__":
      try:
          main()
      except KeyboardInterrupt:
          exit(1)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.