r...@zedat.fu-berlin.de (Stefan Ram) writes: > This C program use a local /static/ variable. > > main.c > > #include <stdio.h> > > int f( void ) > { static int i = 0; > return i++; } > > int main( void ) > { printf( "%d\n", f() ); > printf( "%d\n", f() ); > printf( "%d\n", f() ); } > > transcript > > 0 > 1 > 2 > > When asked how to do this in Python, sometimes people > suggest to use a module variable for this, or to add "i" > to "f" as an attribute, or maybe even to use some kind of > closure. Another (more pythonic?) way to do this, would be: > > main.py > > def f_(): > i = 0 > while True: > yield i > i += 1 > > f = f_() > print( next( f )) > print( next( f )) > print( next( f )) > > transcript > > 0 > 1 > 2
def f(i = [0]): i[0] += 1 return i[0] print(f()) print(f()) print(f()) maybe? More than a bit yucky, though. -- Ben. -- https://mail.python.org/mailman/listinfo/python-list