python - Lambda 用例混淆

标签 python

我一直在玩 Celery/Django。在他们的示例 celery.py 文件中有以下行

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)

其中lambda:settings.INSTALLED_APPSautodiscover_tasks()中形参packages的实参。 settings.INSTALLED_APPS 是一个元组。

autodiscover_tasks() 然后要么调用传递给它的函数,要么直接分配它在第一行之一中给出的变量...

packages = packages() if callable(packages) else packages

所以我的问题是。我只是不明白为什么这样做。显得很多余。为什么不像元组神希望的那样传递 settings.INSTALLED_APPS。为什么要传递一个调用它的匿名函数呢?我在这里缺少什么?

最佳答案

由于 Celery 是异步的,因此 settings.Installed_Apps 在执行其他计算时不会发生变化是不固定的,因此将其包装在 lambda 中将其值封装为引用,直到它被调用。

编辑(添加评论示例):

setting.INSTALLED_APPS = 10
app.autodiscover_tasks(settings.INSTALLED_APPS, force=True) #is called with installed_apps = 10, so it give you an output.

现在想一想,当调用 app.autodiscover_tasks 并进行内部计算时,正在计算其他一些东西,并且 setting.INSTALLED_APPS 现在 = 8,因为您确实使用了该变量,所以您的调用使用的是 10 而不是“8”,但将其封装到 lambda 中(app .autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)) 它会在需要时获取值,与它的实际值同步,应该是8.

关于python - Lambda 用例混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37046966/

相关文章:

python - 同一图中的两个不同图形

python - 如何在python中将html转换为文本?

python - 在python 3中获取素数列表

python - 扭曲的task.loop和pb auth

javascript - 如何将 html 帧捕获为图像

python - 我在哪里可以找到 numpy.where() 源代码?

python - throw [HTTPError : HTTP Error 503: Service Unavailable] Error after the selenium tests are done using Python

python - python读取文件时丢弃 '\n'符号

python - 合并列上的多个数据框

python - 如何用Python创建150万用户的友谊矩阵?