[Python-ideas] PEP-3150
Carl M. Johnson
cmjohnson.mailinglist at gmail.com
Thu Apr 14 13:47:32 CEST 2011
On Wed, Apr 13, 2011 at 10:06 PM, Greg Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> In this particular case (i.e. a function that does nothing
> but define and return another function) I'd like to be able
> to write
>
> def decorator(f)(*args, **kwargs):
> do something...
>
> but that's a subject for another hotly-debated PEP!
Interesting, but could that be extended to support making a throwaway
key function for sorted? With given it's obviously
sorted_list = sorted(original_list, key=keyfunc) given:
def keyfunc(item):
item = item.replace(" ", "")
item = item.lowercase()
...
return item
but I can't see how that your proposal could be expanded beyond the
one use case of decorator making, and today it's already possible to
make a simple decorator decorator that injects f as the first arg:
class MetaDec:
def __init__(self, dec):
self.dec = dec
def __call__(self, f):
def callme(*args, **kwargs):
return self.dec(f, *args, **kwargs)
return callme
@MetaDec
def logger(f, *args, **kwargs):
print("Logging...")
return f(*args, **kwargs)
@logger
def foo():
print("Foo!")
I think the recipe for something like this is already in the docs
somewhere... Obviously, a built-in syntax for simple decorators might
have some savings in efficiency, but I would be surprised if it were
especially noteworthy, since decoration typically happens many fewer
times than function invocation.
Hmm, as I look at the given syntax here again, I find that I don't mind
the extra level of indention. Also, you can add another docstring to
clarify things a bit:
sorted_list = sorted(original_list, key=keyfunc) given:
"A list of widgets sorted by removing whitespace and lowercasing..."
def keyfunc(item):
...
>>> help(sorted_list)
"A list of widgets sorted by removing whitespace and lowercasing..."
More information about the Python-ideas
mailing list