Skip to content

Instantly share code, notes, and snippets.

@sabinem
Last active February 28, 2018 16:55
Show Gist options
  • Save sabinem/26ceead3c02132003f518afccec0c3fd to your computer and use it in GitHub Desktop.
Save sabinem/26ceead3c02132003f518afccec0c3fd to your computer and use it in GitHub Desktop.
Wrapping functions in python
"""
This is a simple example on how to wrap functions in python:
- it uses inspect and wraps from functools
(this is built for python 3.6, you can copy this into a Jupyter notebook and execute!)
"""
# --------------------------------------------------------------------------
# Define the wrapper for logging the function
# --------------------------------------------------------------------------
# importing the libraries
import inspect
from functools import wraps
# this will be the wrapper decorator
def log(f):
"""wrapping a function in order ot log its features"""
# this decorator is from functools, it makes sure that the wrapped function inherits
# important attributes from the function
@wraps(f)
def wrapped_function(*args, **kwds):
# you have to execute the function inside the wrappe
result = f(*args, **kwds)
# now you can print out and collect information on the function:
# collect with magic attributes
print("Function name: {}\n".format(f.__qualname__))
# or collect with the inspect module from python
print("Docstring: {}\n".format(inspect.getdoc(f)))
print("Source code:\n{}\n".format(inspect.getsource(f)))
print("Signature: {}\n".format(inspect.signature(f)))
# you still need to return the result in the wrapper
return result
# now return the wrapper function
return wrapped_function
# --------------------------------------------------------------------------
# Try this with an example:
# --------------------------------------------------------------------------
@log
def example(x, y=3):
"""multiplies the first argument with 2 and adds the second argument"""
return(x*2 + y)
# call the function and see what is logged!
example(3, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment