Jesper Noehr

Pythonista, RESTafarian, Binary Poet & Proud Bucketeer

Python tricks: functools.partial and wraps

with 2 comments

Since Python 2.5, Python has had the ‘functools’ module for doing various higher order functions.

For example:

from functools import partial

def adder(first, second):
	return first + second

adder10 = partial(adder, 10)

print adder10(32) # -> 42

Partial evaluation, eh? That’s kinda cool.

On to ‘wraps’ which is the one I’ve found most practical use for. I like decorators, and I use them where applicable. What I don’t like about decorators is that when you get a backtrace, it’ll actually show up as *that* function, and not the function you decorated.

‘wraps’ to the rescue:

from functools import wraps

def some_decorator(f):
	def wrap(*args, **kwargs):
		return f(*args, **kwargs)
	return wraps(f)(wrap)

@some_decorator
def some_function():
	...

Now the function name, docstring, signature, etc. will be that of ‘f’, no longer ‘wrap’! Immensely useful.

Written by jespern

January 25th, 2009 at 7:23 pm

Posted in python

2 Responses to 'Python tricks: functools.partial and wraps'

Subscribe to comments with RSS or TrackBack to 'Python tricks: functools.partial and wraps'.

  1. Dude, why not…

    def some_decorator(f):
    @wraps(f)
    def wrap(*args, **kwargs):
    return f(*args, **kwargs)
    return wrap

    ?

    Matt

    3 Feb 09 at 12:08 am

  2. Matt,

    That’s the same thing, I know, I wrote the old <2.5 style decorator syntax to fully express what it *does* – it’s already complicated enough without the syntactic sugar, imho.

    jespern

    4 Feb 09 at 11:07 am

Leave a Reply