[Python-ideas] @return?
Conrad Irwin
conrad.irwin at googlemail.com
Wed Apr 14 02:23:08 CEST 2010
On 04/13/2010 11:41 PM, Daniel Stutzbach wrote:
> On Tue, Apr 13, 2010 at 4:36 PM, Conrad Irwin
> <conrad.irwin at googlemail.com>wrote:
>
>> A common pattern when creating decorators is something of the form:
>>
>> def decorator(func):
>> def wrapper(*args):
>> func(modulate(args))
>> return wrapper
>>
>
> You might be interested in Michele Simionato's excellent decorator package.
> The above could be written:
>
> import decorator
> def my_decorator(func):
> return decorator.decorator(func, lambda: func(modulate(args)))
>
Of course, everything is more succinct when a lambda can be used instead
of defining a new function; my proposal was to deal with the times when
this shorthand is not available.
As Masklinn suggests, perhaps it would be better to try and get full
anonymous blocks into Python; though I think that that is a futile task.
Naming all functions is very helpful (as anyone who has tried to analyze
call stacks with more than a few anonymous functions can testify) and
most uses I have for passing blocks around can be done adequately, if
unstylishly, with decorators.
On 04/13/2010 11:18 PM, Chris Rebert wrote:
> * Special cases aren't special enough to break the rules.
> You're allowing keyword(s) where it/they would otherwise be illegal,
> which (1) looks strange and (2) begs the question of why keywords
couldn't
> be used elsewhere (e.g. def if(...): ...), [and of course, as for
allowing
> keywords everywhere, down that path lies madness!; not that that's
> part of your proposal, I'm just pointing out the slippery slope.]
This is indeed an issue, whatever change is needed it is clear that
"@return" is something new, and probably dangerous.
There are two ways (as I see it) of thinking about "@return". Firstly it
may be a glorified "return" that works on the function/class defined on
the next line (instead of the optional testlist on the current line).
Secondly it may be as a normal decorator, with the intended intuition
being that after the function definition is completed, a return is
executed with the defined function (just as for a decorator).
Syntactically there seems to be a minor debate to be had between
creating a new keyword '@return' and allowing 'return' after an '@'.
Maybe the choice of which is preferred depends on the perceived utility
of the presented intuitions. In either case, it would cause less
confusion to restrict an @return to by the first in the decorator list:
keyword_decorator: '@' ( 'return' | 'yield' | 'throw' ) NEWLINE
decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
decorators: [ keyword_decorator ] decorator+
Though this does somewhat highlight the fact that it is not a normal
decorator, and perhaps an alternative syntax that makes this clearer
should be considered. I am not sure I can find anything more elegant.
Conrad
More information about the Python-ideas
mailing list