How to avoid "()" when writing a decorator accepting optionalarguments?

G

Giampaolo Rodolà

I've written this decorator to deprecate a function and (optionally)
provide a callable as replacement

def deprecated(repfun=None):
"""A decorator which can be used to mark functions as deprecated.
Optional repfun is a callable that will be called with the same args
as the decorated function.
"""
def outer(fun):
def inner(*args, **kwargs):
msg = "%s is deprecated" % fun.__name__
if repfun is not None:
msg += "; use %s instead" % (repfun.__name__)
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
if repfun is not None:
return repfun(*args, **kwargs)
else:
return fun(*args, **kwargs)
return inner
return outer


Now, I can use my decorator as such:

@deprecated()
def foo():
return 0

....or provide an optional argument:

@deprecated(some_function)
def foo():
return 0

....but I don't know how to modify it so that I can omit parentheses:

@deprecated
def foo():
return 0

Any hint?


--- Giampaolo
http://code.google.com/p/pyftpdlib/
http://code.google.com/p/psutil/
 
Z

zeekay

I wrote a little library that does this a couple weeks ago, it's on
pypi: http://pypi.python.org/pypi/Decorum/. It's pretty simple, the
last example illustrates how to do what you want. After thinking about
it though, I think it's probably not a great idea to allow the
parenthesis to be omitted.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top