35
def some_function():
    some_dict = {'random': 'values'}
    a = some_dict['random']
    return a
  1. When is the dictionary some_dict created in the memory? (first time the function is called?)

  2. When is the dictionary some_dict destroyed/de-allocated? (when the function returns?)

If so, does that mean the dictionary object will be created every time the function is called?

  1. Should I worry about such things when learning/dealing with python?

    • What is the best practice to deal with such situations? Is it better to create the dictionary globally to avoid creation and destruction of the dictionary every time the function is called?
  2. Where do I learn about such details of a language? I tried looking in the docs but couldn't find what I was looking for.

It would be appreciated if you could answer all 4 of the above questions!

martineau
  • 119,623
  • 25
  • 170
  • 301
oxalorg
  • 2,768
  • 1
  • 16
  • 27
  • This thread might give you a brief idea about your issue : http://stackoverflow.com/a/20819302/4515274 – Rishi Deorukhkar Dec 23 '15 at 07:20
  • Also see [What is the Python equivalent of static variables inside a function?](http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function) and the Linked questions on that page. – PM 2Ring Dec 23 '15 at 11:34

2 Answers2

22
  1. The dictionary some_dict will be created in memory every single time the function is called.
  2. It is deallocated when the function returns.
  3. It is really expensive to recreate the dictionary every single time that the function is called, especially if the dictionary is large. You can instead create the dictionary in the caller function (assuming that the caller itself is only called once) and pass it as a argument to the function some_function().

For example, consider the function caller() which calls the function callee (some_function() in your question), as in

def caller():
    callee()

From your usage case, we want to call callee() multiple times, and we need to reuse the same dictionary in callee(). Let's run through the normal usage cases.

1. Dictionary is generated in callee(). This is the example in your question.

def caller():
    for loop:    
        callee()

def callee():
    generate dictionary
    do something with dictionary

In this case, every single time callee() is called, you have to generate a new dictionary. This is because as soon as callee() returns, all of its local variables are deallocated. Therefore, you can't "reuse" the same dictionary between different callee()s.

2. Dictionary is generated in caller() and passed as an argument to callee().

def caller():
    generate dictionary
    for loop:    
        callee(dictionary)

def callee(dictionary):
    do something with dictionary

In this case, you are generating the dictionary once in caller(), and then passing it to every single callee() function. Therefore, each time that you call callee(), you won't need to regenerate the dictionary.

The dictionary is passed by reference, so you aren't passing a huge data structure each time you call callee(). I'm not going to go in depth about this (you can find a good explanation here), but in essence, there is negligible cost to pass the dictionary as a parameter to callee().

The Obscure Question
  • 1,134
  • 11
  • 26
  • 1
    ...and there are closures as well who can keep the objects alive even though the function that defined them has already returned. – Ashwini Chaudhary Dec 23 '15 at 07:28
  • I do not understand the idea of placing the dictionary in the callee function, because I will still need to call `some_function()` multiple times. Could you please give me an example. – oxalorg Dec 23 '15 at 07:30
  • Thank you very much. I got confused because your answer said "dictionary in the callee function" which you fixed to 'caller function' in the edit. It all makes sense now. Thank you very much! – oxalorg Dec 23 '15 at 10:25
  • 1
    That was a mistake on my part, sorry about that. Glad my answer helped! – The Obscure Question Dec 23 '15 at 10:26
4

When is the dictionary some_dict destroyed/de-allocated? (when the function returns?)

First of all local variables are destroyed as soon as you move away from that scope.

For example in your function when you return you lose all the references to the variables defined like some_dict. Because you are returning a and if you do not have something like a_var = some_function() where a reference would be caught in a_var you would lose a as well.

When is the dictionary some_dict created in the memory? (first time the function is called?)

some_dict = {'random': 'values'} # right here for every method call.

Should I worry about such things when learning/dealing with python?

yes, check the below example

>>> dictionary = {1: 1, 2: 2}
>>> def function():
    dictionary = {1: 2, 2:1}
    print dictionary
>>> function()
{1: 2, 2: 1}
>>> dictionary
{1: 1, 2: 2}

here you might have assumed that you are re assigning the dictionary but python is creating a local dictionary and is lost soon after you return from function

how to over come the above issue, use global it would tell that you are trying to reference object define outside the function.

>>> def function():
    global dictionary
    dictionary = {1: 2, 2:1}
    print dictionary
>>> function()
{1: 2, 2: 1}
>>> dictionary
{1: 2, 2: 1}

Where do I learn about such details of a language? I tried looking in the docs but couldn't find what I was looking for.

probably the question should be how do I learn such details, simple with practice and understand the documentation and read over again.

Rich
  • 12,068
  • 9
  • 62
  • 94
saikumarm
  • 1,565
  • 1
  • 15
  • 30
  • 3
    `global` is a bad recommendation, it's always better to pass the object to the function. – Ashwini Chaudhary Dec 23 '15 at 07:27
  • 1
    Can you explain why global a bad recommendation ? @Ashwini – saikumarm Dec 23 '15 at 07:30
  • 3
    @saikumarm if your project is gaining size and you are importing your former prject as a model to other projects you'll run into trouble with probably several instances of the objects, all relating to a single store, your global variable. Imagine two or three instances reading and writing the same value. Might be really hard to debug such a mess. hmmm? I'm sure there a lot of other issiues with globals but this is the most obvious to me. – Cutton Eye Oct 29 '18 at 10:14
  • The first sentence isn't really true. Local names go out of scope when the function exits; the object referenced by the local name only gets destroyed if no other reference to the object exists. – chepner Sep 13 '20 at 21:49