On 23/06/2018 14:32, Stefan Ram wrote:
r...@zedat.fu-berlin.de (Stefan Ram) writes:
def f():
def g():
g.x += 1
return g.x
g.x = 0
return g
Or, "for all g to share the same x":
main.py
def f():
def g():
f.x += 1
return f.x
return g
f.x = 0
OK, problem solved: we just use attributes of function objects rather
than locally static variables (I didn't even know that was possible).
These apparently can be created, accessed and modified from anywhere in
the program.
The only provisos are that functions with 'static' must be written as
nested functions and the name of the function must be returned via the
enclosing function in some setup code.
The initialising of the static is showed as happening in global space in
your example, but may be possible to move that to the enclosing
function. (For example, when the static data is a local table.)
However, here's a reminder of what the feature looks like implemented
properly:
def g()
static x = 0
x += 1
return x
print (g())
No set up of g needed. 'static' can be added to any existing function
without changing how its used. And it can be removed without having to
dismantled all the extra machinery.
/And/ the access to x inside g() can be a fast local lookup not an
attribute lookup (unless implemented on top of global variables).
--
bart
--
https://mail.python.org/mailman/listinfo/python-list