Skip to content

Instantly share code, notes, and snippets.

@wynemo
Last active December 18, 2015 10:09
Show Gist options
  • Select an option

  • Save wynemo/5766406 to your computer and use it in GitHub Desktop.

Select an option

Save wynemo/5766406 to your computer and use it in GitHub Desktop.

decorators

####closure in python

def generate_power_func(n):
    def nth_power(x):
        return x**n
    return nth_power

get a new function

raised_to_4 = generate_power_func(4)

now delete generate_power_func

>>> del generate_power_func
>>> raised_to_4(2)
16

dig deeper

>>> raised_to_4.__closure__[0].cell_contents
4

http://www.shutupandship.com/2012/01/python-closures-explained.html

####wrapper

example

import functools
def logging(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print func.__name__
        return func(*args, **kwargs)
    return wrapper

now use decorator

@logging
def foo():
    pass

or

foo = logging(foo)

if use functools.wraps:

>>> print foo.__name__
foo

else

>>> print foo.__name__
wrapper

import flask import functools

app = flask.Flask(name)

def handler_logger(f): @functools.wraps(f) def g(*args, **kwargs): print 'before request' r = f(*args, **kwargs) print 'after request' return r return g

@app.route('/') @handler_logger def root(): return 'Hello World'

@app.route('/wtf') @handler_logger def wtf(): return 'I bought a watch last year'

def main(): app.run(port=7777)

if name == 'main': main()

def suppress_errors(log_func): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: log_func(str(e)) return wrapper return decorator

foo = suppress_errors(log_func)(foo)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment