Commits

Marco Lui committed 16d90bc

added a decorator for function progress

Comments (0)

Files changed (1)

src/consoleLog/consoleLog.py

     def __exit__(self, exc_type, exc_value, traceback):
         self.logger.finish()
 
+class LoggedFunction(object):
+    """
+    A higher-order function used to invoke consoleLog messages around the 
+    execution of a particular function.
+    """
+    def __init__(self, logger, decoratee, start_message = None):
+        self.logger = logger
+        self.decoratee = decoratee
+        self.start_message = start_message
+
+    def __call__(self, *args, **kwargs):
+        if self.start_message is None:
+            self.logger.start('Calling '+self.decoratee.__name__)
+        else:
+            self.logger.start(self.start_message)
+        # TODO: Find a way to put logger into the function's scope
+        self.decoratee(*args, **kwargs)
+        self.logger.finish()
+
 class ConsoleLogger(object):
     """
     A console logging object, which can optionally be given an output stream
         """
         return ConsoleLevel(self, message)
 
+    def with_log(self, arg):
+        """
+        Decorator which allows notification of calling and completion of the
+        decorated function. Can be called with an optional string argument to 
+        specify a custom 'start' message.
+        """
+        if callable(arg):
+            return LoggedFunction(self, arg)
+        else:
+            return lambda decoratee: LoggedFunction(self, decoratee, arg)
+
     def start(self, message, nSteps=None):
         """
         Starts a new hierarchical logging section. Every call to start() must