[Python-ideas] Delay evaluation of annotations

Chris Angelico rosuav at gmail.com
Thu Sep 22 22:54:14 EDT 2016


On Fri, Sep 23, 2016 at 12:35 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> The straight-forward and simple way of writing a recursive spam()
> function surprises beginners, but they might go years or their entire
> career without running into a situation where they are caught by
> surprise. After all, it is rare for productuon code to rename functions,
> and rarer still to do it to recursive functions:
>
>     func = spam
>     spam = something_else()
>     func()  # why does the recursion not work???
>
> In production code, that sort of thing almost never happens.

There's actually one very common technique involving rebinding functions.

@count_calls
def mergesort(lst):
    mid = len(lst) // 2
    if not mid: return lst
    return merge(mergesort(lst[..mid]), mergesort(lst[mid..]))

*Obviously* this is recursive. But if you used some magic that said
"call the function that's currently being called", you'd be bypassing
the count_calls decoration (which would presumably work by creating a
wrapper function). Yes, it may defeat some potential optimizations (eg
tail recursion optimization), but it enables all this flexibility.

So we _need_ to have this kind of rebind available, and not just for experts.

> In the meantime, I'll usually just write my recursive functions the
> old-fashioned normal way.

As will I. Of course, people are welcome to work differently, just as
long as I never have to write tests for their code, or refactor
anything into a decorator, or anything like that. I want the
POWAH!!!!! :)

ChrisA


More information about the Python-ideas mailing list