Python return values

Mel mwilson at the-wire.com
Mon Jan 5 18:09:01 CET 2009


koranthala at gmail.com wrote:

> I have a newbie doubt about Python return values.
> 
> In (say) C/C++, if we try to return a value which is stored inside the
> procedure stack, we will get an error when trying to access it outside
> of that procedure.
> For example:
> function foo():
>    dcl y int
>    dcl x pointer to int pointing to y
>    return x
> 
> 
> function bar():
>    x = foo()
>    ...
>    use x
> 
> This will error out since the memory has be taken back.
> 
> Now, in Python, we do it everytime, because all variables are
> references, and even returns just copies the references.
> function pyfoo():
>   return 786
> 
> function pyfoo1():
>   x = xclass()
>   return x
> 
> function pybar():
>   x = pyfoo()
>   y = pyfoo1()
>   ...
>   use x, y
> 
> Why doesnt it error out?

Because Python doesn't use the procedure stack that way.  Using C/C++ terms,
all objects are in the heap, and objects are deallocated automatically
after all references to them disappear.

        Mel.




More information about the Python-list mailing list