def some_function():
some_dict = {'random': 'values'}
a = some_dict['random']
return a
When is the dictionary
some_dict
created in the memory? (first time the function is called?)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?
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?
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!
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 returninga
and if you do not have something likea_var = some_function()
wherea
reference would be caught ina_var
you would losea
as well.some_dict = {'random': 'values'} # right here for every method call.
yes, check the below example
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
probably the question should be
how do I learn such details
, simple with practice and understand the documentation and read over again.some_dict
will be created in memory every single time the function is called.some_function()
.For example, consider the function
caller()
which calls the functioncallee
(some_function()
in your question), as inFrom your usage case, we want to call
callee()
multiple times, and we need to reuse the same dictionary incallee()
. Let's run through the normal usage cases.1. Dictionary is generated in
callee()
. This is the example in your question.In this case, every single time
callee()
is called, you have to generate a new dictionary. This is because as soon ascallee()
returns, all of its local variables are deallocated. Therefore, you can't "reuse" the same dictionary between differentcallee()
s.2. Dictionary is generated in
caller()
and passed as an argument tocallee()
.In this case, you are generating the dictionary once in
caller()
, and then passing it to every singlecallee()
function. Therefore, each time that you callcallee()
, 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 tocallee()
.