On 2021-05-28 04:53, Steven D'Aprano wrote:
On Thu, May 27, 2021 at 07:13:56PM -0700, Brendan Barnwell wrote:
On 2021-05-27 14:33, Steven D'Aprano wrote:
But even if we did have actual constants, how does that help get static *variables*, you know, things that aren't constant but can vary?
All of those use cases can already be handled with a class that stores its data in an attribute.
And with one sentence you have just explained why Python doesn't have closures or generators. There is nothing that they do that can't be handled by a class.
Oh wait, Python does have closures (since version 1.5) and generators (since 2.2). Maybe your argument "just use a class" isn't quite as convincing as you hoped.
I see your point, but I don't agree that static function variables are parallel to either closures or generators.
Closures are, to my mind, just an outgrowth of Python's ability to define functions inside other functions. If you're going to allow such nested functions, you have to have some well-defined behavior for variables that are defined in the other function and used in the inner one, and closures are just a reasonable way to do that.
As for generators, they are tied to iteration, which is a pre-existing concept in Python. Generators provide a way to make your own functions/objects that work in a `for` loop in a manner that naturally extends the existing iteration behavior of lists, tuples, etc.
The proposal for static function variables is quite different. It does not hook into or extend any existing control flow structure as generators do, nor is it necessary to ground allowed syntax as closures are. It's just a new proposal to add a totally new behavior to functions. And the behavior that it adds --- storing state --- is exactly what attributes are already used for across all kinds of contexts in Python. So it's not just that you can theoretically contort your code to use classes and attributes instead of using static function variables. It's that classes and attributes are already designed to do and already do exactly what static function variables are supposedly going to do, namely store state across multiple calls.
Also, although I haven't used dataclasses extensively, it seems that dataclasses would provide a pretty simple way of doing this, since they provide a concise way of specifying the necessary attributes so you don't need to write an `__init__`. It's true there is a small additional cost in that you'd have to instantiate the class and then access your "static variables" as `self.blah` instead of as a local variable `blah`, but that minor increase in verbosity doesn't, to me, justify the creation of static function variables as a whole new language construct.