Skip to content

Instantly share code, notes, and snippets.

@wware
Created October 16, 2014 15:51
Show Gist options
  • Save wware/99b923412d48681c03a8 to your computer and use it in GitHub Desktop.
Save wware/99b923412d48681c03a8 to your computer and use it in GitHub Desktop.
Python closures and decorators - really broken, or simply horrible?
from functools import wraps
# A decorator without an argument.
def add_four(f):
@wraps(f)
def wrapped(x):
y = f(x)
return y + 4
return wrapped
@add_four
def addSix(x):
return x + 6
assert addSix(5) == 15
# A decorator with an argument.
def add(n):
def decorator(f):
@wraps(f)
def wrapped(x):
y = f(x)
return y + n
return wrapped
return decorator
@add(4)
def addSix(x):
return x + 6
assert addSix(5) == 15
# This closure works, meaning that the "n" in the inner function
# correctly references the "n" in the outer function.
def make_adder(n):
def created_func(x):
return x + n
return created_func
f = make_adder(3)
assert f(4) == 7
# Hack to pass an extra parameter into a variadic function.
# Surprisingly, this works! Will it work in a Qt environment?
def foo(bar):
def foo_1(*args):
return (foo_1.bar, args)
foo_1.bar = bar
return foo_1
f = foo("abc")
assert f("def", "ghi") == ('abc', ('def', 'ghi'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment