Static variables [was Re: syntax difference]

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jun 23 23:19:45 EDT 2018


On Sat, 23 Jun 2018 18:29:51 +0100, MRAB wrote:

> You can already do something similar like this:
> 
> def f():
>       f.x += 1
>       return f.x
> f.x = 0
> 
> [snip]

You can, but only as an illustration, not as a serious implementation.

The whole point of static local variables is that they are:

(1) Local variables, and hence FAST;

(2) fully encapsulated inside the function.

Using f.x fails on both accounts:

- it requires a global name lookup for "f" (hence slow);

- followed by an attribute lookup for "x" (hence even slower);

- f.x is not encapsulated inside the function. It requires initialisation 
outside the function. The attribute f.x is easily visible to the caller.

(Technically, so probably would static variables, but only by inspecting 
the function's internals. People know they're on thin-ice if they mess 
with them. And if we really needed to, we could protect the static 
storage inside the function from writing, if not reading, as we do with 
closures. f.x looks like an ordinary attribute.)

I have used the f.x trick before, for things where speed was not 
critical, but I've never really loved the idea, and it certainly cannot 
be used as a replacement of the def func(arg, len=len, int=int) 
optimization trick.


-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list