[Python-ideas] Persisting private function state between calls (was: "Read Only" namespaces)
Steven D'Aprano
steve at pearwood.info
Sat Mar 29 19:58:25 CET 2014
On Sat, Mar 29, 2014 at 12:39:31PM -0600, Eric Snow wrote:
> On Sat, Mar 29, 2014 at 9:51 AM, Richard Prosser
> <richard.prosser at mail.com> wrote:
> > Quite simply, the principle is to allow changes to variables within a
> > function body (for example) but not outside of it, rather like the
> > Functional Programming paradigm. That of course excludes the use of global
> > variables and requires functions to return whatever is needed to the outer
> > scope. In my experience, globals are only needed to implement persistent
> > (inter-call) states anyway, so assuming that such a feature is available in
> > the language I believe that the "Read Only" proposal is viable.
>
> To restate, you want a way to have some variables in your function
> body that persist between calls without using global variables.
Ah-ha! That makes sense now. Thank you!
> 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.
A much better solution if you need persistent state is to encapsulate
the function and state into an object:
class Adder:
def __init__(self):
self.current = 0
def add(self, x):
self.current += x
return self.current
Then you can have as many Adder instances as you want, without them all
sharing state.
adder1 = Adder().add
adder2 = Adder().add
[...]
> 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.
--
Steven
More information about the Python-ideas
mailing list