static variables

Steven D'Aprano steve at pearwood.info
Wed Dec 2 05:22:32 EST 2015


On Wed, 2 Dec 2015 07:34 pm, Antoon Pardon wrote:

> Op 02-12-15 om 02:24 schreef Steven D'Aprano:
>> Heh, I agree, and as I suggested, it might be good to have an actual
>> mechanism for static locals. But using a class is no better: your "static
>> storage" is exposed as an instance attribute, and even if you flag it
>> private, *somebody* is going to mess with it.
> 
> Why don't you invoke the consenting adults now? 

Because I don't wish to.

I can invoke consenting adults to defend people drinking soft drinks and
eating chocolate, doesn't mean I have to invoke consenting adults to defend
the practice of middle-class film-makers goading homeless people into
fighting and other dangerous acts for trivial amounts of money.

https://en.wikipedia.org/wiki/Bumfights


> People have come here 
> arguing for all kind of extra features, which would somehow defend
> against messing with certain variable or attributes the author wants
> protected. The general respons has always been, that we are consenting
> adults here.

Yes, and that's fine. Consider the word *judgement* -- in our (the
collective community) judgement, certain things are acceptable for
consenting adults and others are not. 

But if it makes you feel better, if I were to champion this feature, I would
suggest that the initialised static variable be stored in a writable dunder
attribute of the function, just like default values are today. If you
wanted to inspect, or even modify, the static variables, you could access
function.__static__[x].


> Static variables, are just a feature to protect what is essentially
> a global variable against messing from somewhere else.

No, that's not the reason for static variables. The primary reasons for
static variables are efficiency and encapsulation.

Efficiency: consider a function that requires a considerable amount of
initialisation, which only needs to be done once. In older languages like
Pascal which lack static variables, you might perform that initialisation
every time you call the function. Or, you might break encapsulation by
storing something that belongs with the function outside the function.
Static variables let you have your cake and eat it too: you can keep the
variable with the function, avoiding namespace pollution, which still
allowing the efficiency of having that variable calculated once only.


> So why is 
> this feature worthy of discussion and others are not?

Because I say so. Since it's my suggestion, that's the only reason I need.

 

-- 
Steven




More information about the Python-list mailing list