On Thu, May 27, 2021 at 11:17:18AM +0200, Ronald Oussoren via Python-ideas wrote:
For this particular question/proposal: “static” variables in functions in C like languages are basically hidden global variables, and global variables are generally a bad idea.
Python is not required to use the same design mistakes as C :-)
Shreyan already said that static variables in a function should be local to that function. The semantic difference compared to regular locals is that they should persist from one call to the next.
Aside from globals, which we agree are Considered Harmful, you've suggested two alternative implementations:
- something with closures;
- hidden state in an object with a `__call__` method.
Closures are cool, but the hidden state really is inaccessible from outside the function. (At least I've never worked out how to get to it.) So the callable object is better for introspection and debugging.
Functions are objects with a `__call__` method, and they already have persistent state!
>>> def spam(arg="Hello world"): ... pass ... >>> spam.__defaults__ ('Hello world',)
We could, I think, leverage this functionality to get this.