Those of you who were at the clinic last night know that I
was asking for help on a weird limitation of Python.
The problem: Consider the function, foo(), in this C program.
#include <stdio.h>
int foo()
{
static int n = 0;
return ++n;
}
main()
{
int n1 = foo();
int n2 = foo();
printf("%d %d\n", n1, n2);
return 0;
}
It keeps state around between calls, but does not have extra names in
any nonlocal namespaces.
How would you write a function in Python that does the same?
(Note, I don't want a solution that only returns successive numbers.
I might use this to return successive lines of a file or calculate
successive permutations of a sequence or whatever.)
The solution: For some reason, this apparently simple problem doesn't
have any good solutions (that I'm aware of). Here's the best I can
do.
def foo():
n = [0]
def bar():
n[0] += 1
return n[0]
return bar
foo = foo()
That reuses the single global name, foo. First, foo holds a function
that returns the function we need. Then we set foo to the returned
function. The original function is not accessible, AFAIK.
--
Bob Miller K<bob>
kbobsoft software consulting
http://kbobsoft.com [EMAIL PROTECTED]
_______________________________________________
Eug-LUG mailing list
[EMAIL PROTECTED]
http://mailman.efn.org/cgi-bin/listinfo/eug-lug