Static variables [was Re: syntax difference]

Chris Angelico rosuav at gmail.com
Sat Jun 23 16:13:16 EDT 2018


On Sat, Jun 23, 2018 at 10:41 PM, Bart <bc at freeuk.com> wrote:
> This is an example of a simple concept getting so out of hand that it will
> either never be implemented, or the resulting implementation becomes
> impractical to use.
>
> This is what we're trying to do:
>
>     def nextx():
>         static x = 0
>         x += 1
>         return x
>
> And this is the simplest equivalent code in current Python that will cater
> for 99% of uses:
>
>     _nextx_x = 0
>
>     def nextx():
>         global _nextx_x
>         _nextx_x += 1
>         return _nextx_x
>
> No nested functions. No generating new instances of functions complete with
> a new set of statics each time you happen to refer to the name. (Which
> sounds to me as useful as creating a new instance of an import when you copy
> its name, complete with a separate set of its globals. Isn't this stuff what
> classes are for?)
>
> (At what point would that happen anyway; if you do this:
>
>     g = nextx              # hypothetical version would static
>
> it will create a new instance of 'nextx'. But it won't create one here, just
> before () is applied:
>
>     nextx()         # ?
>
> Or how about here:
>
>     listoffunctions = (nextx1, nextx2, nextx3)
>
>     listoffunctions[i]()     # ?
>
> )

Clearly you have completely misunderstood the entire concept of
Python's memory model, so I am not going to engage in debate with you
on this. This is my ONLY post explaining this to you.

NONE of your examples are taking copies of the function. They all are
making REFERENCES to the same function. That is all.

Creating new functions is the job of 'def' and 'lambda'. Not
assignment. So the concept of "multiple functions with the same name"
comes from executing the def statement more than once.

ChrisA



More information about the Python-list mailing list