Mutable defaults
Grant Edwards
grant.b.edwards at gmail.com
Wed Feb 10 21:22:13 EST 2021
On 2021-02-11, J. Pic <jpic at yourlabs.org> wrote:
> I just meant removing the whole "default value mutating" story, not
> removing mutable variables. Really, I was wondering if there was a use case
> where this actually turns to an advantage,
I've seen people show how it can be used to provide function-scope
persistent storage -- the equivalent of declaring a static variable in
a C function. I don't think I've seen that done in the wild, though.
class StaticStorage():
pass
def foo(static=StaticStorage()):
if not hasattr(static,'x'):
static.x = 0
static.x += 1
return static.x
print(foo())
print(foo())
print(foo())
print(foo())
print(foo())
Run that, and it prints:
1
2
3
4
5
More information about the Python-list
mailing list