Function to avoid a global variable

DL Neil PythonList at DancesWithMice.info
Fri May 1 21:06:50 EDT 2020


On 2/05/20 12:00 PM, Bob van der Poel wrote:
> I still think that the use of a keyword like "static" would be easiest.
> 
> def foo(arg):
>      static counter = 0
>      counter += 1
>      if counter ...
> 
> And in this case static just means that it's a variable only readable
> inside foo() and it should maintain it's value between calls. A "global"
> without the name pollution. Or is this too simple .... ???


No, it's not "too simple" an example/request.

Although they are often considered more complex than materials suitable 
for 'beginner' (?simple) training, generator functions (and 
async-gen-func-s) already offer this (without the static-statement)

def gen( args ):
	counter = 0
	while counter < max_depth:
		yield counter

counter will retain its value ("maintain state") between iterations.
-- 
Regards =dn


More information about the Python-list mailing list