On 22 Sep, 10:32, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:

> but it isn't good enough if the function needs to refer to it's own
> state, because functions can only refer to themselves by name and the
> factory can't know what name the function will be bound to.
>
> As far as I know, the only objects that know how to refer to themselves
> no matter what name they have are classes and instances. And instances
> share at least some state, by virtue of having the same class.

Here is a simple way to make a function able to refer to its own
state:

def bindfunction(f):
    def bound_f(*args, **kwargs):
        return f(bound_f, *args, **kwargs)
    bound_f.__name__ = f.__name__
    return bound_f

>>> @bindfunction
... def foo(me, x):
...     me.attr.append(x)
...     return me.attr
...
>>> foo.attr = []
>>> foo(3)
[3]
>>> foo(5)
[3, 5]
>>>

--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to