2

As per my understanding when we return a local variable from a function in python, a reference to that memory location is returned. Also, local variable will/can be deleted by garbage collector once function execution is over. So my question is "Is it safe to return local variable from function in python?" Example:

def func():
    a = 100;
    return a;

val = func();
print val;

Is val having a dangling pointer? Or garbage collector will never delete a memory location if there is a variable pointing to it even if memory is created in stack (inside a function)? In our example variable "a".

Sourabh Saxena
  • 127
  • 1
  • 1
  • 7
  • 3
    Python doesn't create variables "on the stack". – melpomene Mar 31 '17 at 06:45
  • 2
    Where does it create variables? Where can I explore more about it? – Sourabh Saxena Mar 31 '17 at 06:48
  • Short answer: in CPython, all objects (which means *everything* in python) are on the heap. From the [docs](https://docs.python.org/3.6/c-api/memory.html): "It is important to understand that the management of the Python heap is performed by the interpreter itself and that the user has no control over it, even if she regularly manipulates object pointers to memory blocks inside that heap." Even shorter answer: what you are doing is totally safe. As long as your object is still referened, it will not be garbage collected. – juanpa.arrivillaga Mar 31 '17 at 06:55
  • To me, what your doing looks perfectly safe – Tom de Geus Mar 31 '17 at 06:58
  • Thanks or the comments and reference link. – Sourabh Saxena Mar 31 '17 at 07:01

0 Answers0