[Python-ideas] @return?

Conrad Irwin conrad.irwin at googlemail.com
Wed Apr 14 18:41:43 CEST 2010


On 04/14/2010 03:54 PM, spir ☣ wrote:
> On Wed, 14 Apr 2010 01:23:08 +0100
> Well, i'm not 100% sure of the point of view below, but let's take the risk ;-) (Gentle)critics welcome.
> 
> As I see it, the issue you raise is more general than the precise point of a decorator's return value. It is instead deeply rooted in Python's core syntax making func/method  definitions (and classes, too) somewhat different. One doesn't write:
> 
> f = function(): <body>
> 
> So that one cannot write neither:
> 
> return function(): <body>
> 
> This point (together with the unneeded 'return' in this case) also raises the need for a special inline syntax for func defs used in higher-order functions --say for programming in functional style. This a bit of a pity because Python also offers a third syntax for similar semantics with list comprehensions.
> 
> As a counter-example just for reference, Lua's function defs are normal definitions, so that there are no such issues; "return function() <body>" is perfectly valid and even common; there is no need for special inline syntax.
> But:
> * An alternate pattern (function f() <body>) is available for named functions, while unnecessary (I personly never use it).
> * Mainly because of the useless 'return', I guess, some users still argue for a more compact anonymous pattern.
> 
> 
> Denis

As I understand it, there is little desire to allow function definitions
to appear "just anywhere" in Python. It seems to be more of an
aesthetics issue than a technical problem:

    result = register_callback(def success(arg):
                                   print(arg)
                              )

Could "work" (with some jiggling of the lexer), but it's not hugely
pleasant to read, and it gets even worse if you want to decorate the
function, or pass multiple functions. That said, I think it is
significantly nicer than the decorator abuse:

    @register_callback
    def result(arg):
        print(arg)

Concentrating on returning functions exclusively, it seems possible that

    return def foo(bar):
        baz()

    return def(bar):
        baz()

    return foo(bar):
        baz()

Could all work, the last is the least ugly (I think) but also the worst
in terms of answering the "where was foo defined" question. In this
case, the decorator "abuse" is much less of an abuse, mainly because
assigning the return value to something isn't needed:

    @return
    def foo(bar):
        baz()

Changing things so that return isn't necessary at all would also solve
the problem, and quite nicely, but I think that's a far-too-drastic
change in semantics. I suppose one could create a decorator that causes
the last calculation in the function to be returned, it seems a bit too
much like magic though.

Conrad



More information about the Python-ideas mailing list