Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #7455 > unrolled thread
| Started by | Giampaolo Rodolà <g.rodola@gmail.com> |
|---|---|
| First post | 2011-06-11 21:27 +0200 |
| Last post | 2011-06-16 04:10 -0700 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
How to avoid "()" when writing a decorator accepting optional arguments? Giampaolo Rodolà <g.rodola@gmail.com> - 2011-06-11 21:27 +0200
Re: How to avoid "()" when writing a decorator accepting optional arguments? zeekay <zachkelling@gmail.com> - 2011-06-16 04:10 -0700
| From | Giampaolo Rodolà <g.rodola@gmail.com> |
|---|---|
| Date | 2011-06-11 21:27 +0200 |
| Subject | How to avoid "()" when writing a decorator accepting optional arguments? |
| Message-ID | <mailman.133.1307820426.11593.python-list@python.org> |
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/
[toc] | [next] | [standalone]
| From | zeekay <zachkelling@gmail.com> |
|---|---|
| Date | 2011-06-16 04:10 -0700 |
| Message-ID | <3ed49034-ca45-46d6-b2ac-461de5c93d0b@22g2000prx.googlegroups.com> |
| In reply to | #7455 |
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.
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web