简体   繁体   English

函数内局部变量的生命周期(内存范围)

[英]Lifetime (memory scope) of local variables inside a function

def some_function():
    some_dict = {'random': 'values'}
    a = some_dict['random']
    return a
  1. When is the dictionary some_dict created in the memory?什么时候在内存中创建字典some_dict (first time the function is called?) (第一次调用函数?)

  2. When is the dictionary some_dict destroyed/de-allocated?字典some_dict销毁/取消分配? (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?在学习/处理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!如果您能回答以上所有 4 个问题,将不胜感激!

  1. The dictionary some_dict will be created in memory every single time the function is called.每次调用该函数时,都会在内存中创建字典some_dict
  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() .您可以改为在调用者函数中创建字典(假设调用者本身只被调用一次)并将其作为参数传递给函数some_function()

For example, consider the function caller() which calls the function callee ( some_function() in your question), as in例如,考虑调用函数callee (您问题中的some_function()的函数caller() ),如

def caller():
    callee()

From your usage case, we want to call callee() multiple times, and we need to reuse the same dictionary in callee() .从您的使用案例来看,我们想多次调用callee() ,我们需要在callee()重用相同的字典。 Let's run through the normal usage cases.让我们来看看正常的使用案例。

1. Dictionary is generated in callee() . 1.字典在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.在这种情况下,每次callee() ,您都必须生成一个新字典。 This is because as soon as callee() returns, all of its local variables are deallocated.这是因为一旦callee()返回,它的所有局部变量都会被释放。 Therefore, you can't "reuse" the same dictionary between different callee() s.因此,您不能在不同的callee()之间“重用”相同的字典。

2. Dictionary is generated in caller() and passed as an argument to callee() . 2.字典在caller()生成并作为参数传递给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.在这种情况下,您将在caller()中生成一次字典,然后将其传递给每个callee()函数。 Therefore, each time that you call callee() , you won't need to regenerate the dictionary.因此,每次调用callee() ,都不需要重新生成字典。

The dictionary is passed by reference, so you aren't passing a huge data structure each time you call callee() .字典是通过引用传递的,因此每次调用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() .我不会深入讨论这个(你可以在这里找到一个很好的解释),但本质上,将字典作为参数传递给callee()成本可以忽略不计。

When is the dictionary some_dict destroyed/de-allocated?字典 some_dict 何时销毁/取消分配? (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 .例如,在您的函数中,当您返回时,您将丢失对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.因为您正在返回a并且如果您没有像a_var = some_function()这样a东西,其中引用将被捕获在a_var您也会失去a

When is the dictionary some_dict created in the memory?什么时候在内存中创建字典some_dict? (first time the function is called?) (第一次调用函数?)

some_dict = {'random': 'values'} # right here for every method call. some_dict = {'random': 'values'} # 每个方法调用都在这里。

Should I worry about such things when learning/dealing with python?在学习/处理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在这里,您可能已经假设您正在重新分配字典,但是 python 正在创建一个本地字典,并且在您从函数返回后不久就丢失了

how to over come the above issue, use global it would tell that you are trying to reference object define outside the function.如何克服上述问题,使用 global 它会告诉您正在尝试引用函数外部的对象定义。

>>> 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.可能问题应该是how do I learn such details ,简单的练习并理解文档并重新阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM