Self function

wolfram.hinderer at googlemail.com wolfram.hinderer at googlemail.com
Tue May 5 04:35:17 EDT 2009


On 5 Mai, 08:08, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:

> Self-reflective functions like these are (almost?) unique in Python in
> that they require a known name to work correctly. You can rename a class,
> instance or module and expect it to continue to work, but not so for such
> functions. When editing source code, it is very easy to forget to change
> all the references to the function name within the body of itself
> function, even for small functions, and refactoring tools are overkill.

It is easy to change all references of the function name, except for
those in the function body itself? That needs some explantation.

> It is often useful to create two similar functions, or a variant of a
> function, without duplicating the source code. E.g. you might want a
> function that uses a cache, while still keeping around the version
> without a cache:
>
> cached_function = memoize(function)
>
> Currently, this does not give the expected results for recursive
> functions, nor does it give an error. It simply fails to behave as
> expected. Re-writing function() to use __this__ for the recursive call
> will solve that problem.

Won't __this__ (inside function) still refer to function, not
cached_function?

> Here is a proof-of-concept pure Python implementation, using a decorator,
> and abusing a global variable. This is NOT to imply that `__this__`
> should be a global if this proposal goes ahead.
>
> from functools import wraps
> def make_this(func):
>     global __this__
>     __this__ = func
>     @wraps(func)
>     def f(*args, **kwargs):
>         return func(*args, **kwargs)
>     return f

This still has the memoizing problem.



More information about the Python-list mailing list