Logging each in/out of each function
<p>Currently I typically add a log line to my functions with details of the variables that are inputted and returned. However I am looking for an elegant way around this.</p>

<p>Is there a way to log each input to a function and what is returned using some form of magic methods?</p>

<p>Below is an example,</p>

<pre><code>class exampleclass(object):
    def __init__(self,size=False):
        self.size = size

    def funt1(self,weight=None):
        return weight

    def funt2(self,shape=None):
        return shape
</code></pre>

<p>Here I want to log the returned variable and also what is inputted for each function using the smallest amount of code possible.</p>

<p>There is a concept of <a href="https://wiki.python.org/moin/PythonDecorators" rel="nofollow">decorators in python</a>. They help you abstract out the common code you want to inject on any function on your will. Make a decorator named <code>log</code> as follows:</p>

<pre><code>import logging
from functools import wraps

def log(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
            logging.debug("args - %s", str(args))
            logging.debug("kwargs - %s", str(kwargs))
            response = func(self, *args, **kwargs)
            logging.debug("response - %s", str(response))
            return response
    return wrapper
</code></pre>

<p>Now, you can use this decorator for any function as follows:</p>

<pre><code>@log
def funt1(self,weight=None):
    return weight
</code></pre>

<p>The above code will log all the arguments &amp; their returned values with just 1 line of code.</p>

<p><a href="http://thecodeship.com/patterns/guide-to-python-function-decorators/" rel="nofollow">Here</a> is a good blog on understanding decorators.</p>

python