[Python-ideas] Persisting private function state between calls (was: "Read Only" namespaces)

Eric Snow ericsnowcurrently at gmail.com
Sat Mar 29 20:14:22 CET 2014


On Sat, Mar 29, 2014 at 12:58 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Mar 29, 2014 at 12:39:31PM -0600, Eric Snow wrote:
>> There are already several ways to do this, though none is particularly
>> obvious.
>
> I disagree -- I think your example of an adder() function with a global
> is extremely obvious. It seems to be the usual solution that most
> beginners go for. It's not a *good* solution, but it is simple and
> obvious.

Agreed.  It was the example that mapped most closely to how the OP
described his problem. :)

[...]

>> A more explicit mechanism could be nice, but would have to pass a
>> pretty high bar for inclusion into the language.  Here are some
>> approaches:
>>
>> * A new keyword, e.g. "persistent", to accompany global and nonlocal.
>> * A special decorator that identifies persistent local variables in
>> the function.
>
> -1 to both of those. Not every idiom needs a keyword.

Oh, I agree*.  I should have made it clear. :)  I would advocate
instead for a more general solution such as that provided by statement
local namespaces (e.g. PEP 3150/403).

-eric

* I do think it may be worth exploring the idea of special decorators
that set code/function object flags that influence special-case
behaviors.  However, the performance implications of handling such
flags at call-time *may* render the idea impractical.


More information about the Python-ideas mailing list