Functions continuing to ru after returning something?

Peter Otten __peter__ at web.de
Tue Aug 31 10:03:54 CEST 2010


Bradley Hintze wrote:

> I may be having a brain fart, but is it at all possible to have a
> function first return a value then continue its calculation. Like this
> simple example:
> 
> my_var = 5
> def my_function():
>     return my_var
>     my_var +=1
> 
> This obviously won't work as written but is there a cleaver way around
> this.

>>> n = 1
>>> def f():
...     global n
...     try:
...             return n
...     finally:
...             n += 1
...
>>> f()
1
>>> f()
2
>>> f()
3

However, I would prefer the generator as Aidan has shown because it doesn't 
rely on a global variable.

Peter




More information about the Python-list mailing list