472,096 Members | 1,920 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,096 software developers and data experts.

functools's partial and update_wrapper does not work together

Hello!

I wanted to use a decorator to wrap partially applied function like
this:
from functools import *

def never_throw(f):
@wraps(f)
def wrapper(*args, **kwargs):
try: return f(*args, **kwargs)
except: pass
return wrapper

def foo(i):
raise ValueError(str(i) + " is too little")

never_throw(partial(foo, 3))

However this fails with an exception saying
AttributeError: 'functools.partial' object has no attribute
'__module__'.

How can I use generic wrapper (never_throw) around partials?

Thank you,
Piotr
Aug 21 '08 #1
2 2698
pi*************@gmail.com a écrit :
Hello!

I wanted to use a decorator to wrap partially applied function like
this:
from functools import *

def never_throw(f):
@wraps(f)
def wrapper(*args, **kwargs):
try: return f(*args, **kwargs)
except: pass
Not an answer to your question, but: by all means, *never* use bare
except clauses. Please remember that SysExit and KeyboardInterrupt are
exceptions too.
return wrapper

def foo(i):
raise ValueError(str(i) + " is too little")

never_throw(partial(foo, 3))

However this fails with an exception saying
AttributeError: 'functools.partial' object has no attribute
'__module__'.

How can I use generic wrapper (never_throw) around partials?
If not already done by someone else, it might be worth filling a ticket
- generic decorators should work with any callable, not only with
functions (well, IMHO at least).

A possible workaround is:

_dont_pass = (
SysExit,
KeyboardInterrupt,
OtherStuffYouDontWantToPassSilentyHere,
)

def never_throw(f):
"""well... almost never..."
try:
f.__module__
except AttributeError:
f.__module__ = "whatever"
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception, e:
if isinstance(e, _dont_pass):
raise

HTH
Aug 21 '08 #2
If not already done by someone else, it might be worth filling a ticket
- generic decorators should work with any callable, not only with
functions (well, IMHO at least).
you're right. it's already there http://bugs.python.org/issue3445

regards!
Aug 21 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.