Functionality like local static in C
Mirko
mirkok.lists at googlemail.com
Thu Apr 14 12:52:08 EDT 2022
Am 14.04.2022 um 17:02 schrieb Cecil Westerhof via Python-list:
> In C when you declare a variable static in a function, the variable
> retains its value between function calls.
> The first time the function is called it has the default value (0 for
> an int).
> But when the function changes the value in a call (for example to 43),
> the next time the function is called the variable does not have the
> default value, but the value it had when the function returned.
> Does python has something like that?
>
There are several ways to emulate that:
### With a mutable default argument
In [1]: def func(var=[-1]):
...: var[0] += 1
...: return var[0]
...:
In [2]: func()
Out[2]: 0
In [3]: func()
Out[3]: 1
In [4]: func()
Out[4]: 2
### with a callable class
In [12]: class Func():
...: def __init__(self, var=-1):
...: self.var = var
...:
...: def __call__(self):
...: self.var += 1
...: return self.var
...:
In [13]: func = Func()
In [14]: func()
Out[14]: 0
In [15]: func()
Out[15]: 1
In [16]: func()
Out[16]: 2
### with a closure
In [29]: def outer(var=-1):
...: def inner():
...: nonlocal var
...: var += 1
...: return var
...: return inner
...:
In [30]: func = outer()
In [31]: func()
Out[31]: 0
In [32]: func()
Out[32]: 1
In [33]: func()
Out[33]: 2
### with a generator
In [2]: def func(init=0, end=3):
...: for var in range(init, end):
...: yield var
...:
In [3]: for i in func():
...: print(i)
...:
0
1
2
HTH
More information about the Python-list
mailing list