Python 中的 **kwargs 是急切的还是懒惰的?
我正在尝试执行 Django 查询:
#att.name is a string
kwargs = {att.name : F('node__product__' + att.name) }
temps = Temp.objects.exclude(**kwargs)
我想知道这是否正确。到目前为止,我看到的所有示例都在值中使用字符串,但是如果该值是一个函数,我应该将值设置为字符串吗?像这样?
kwargs = {att.name : 'F('node__product__' + att.name)' }
值中的函数是在参数列表中立即执行还是等到需要时才执行?
I'm trying to execute a Django query:
#att.name is a string
kwargs = {att.name : F('node__product__' + att.name) }
temps = Temp.objects.exclude(**kwargs)
I'm wondering if this is correct. All the examples I've seen so far use strings in the values, but what if the value is a function, should I make the value a string, like this?
kwargs = {att.name : 'F('node__product__' + att.name)' }
Does the function in the value get executed eagerly in the argument list or does it wait until it's needed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 python 中,表达式总是被急切地求值。 python 中没有惰性求值。一些库通过允许应该属于某种特定类型的值改为字符串(稍后对其进行评估)来解决此有用功能的缺失。您可以通过这种方式声明 django 模型的某些部分(以便可以声明相互引用的外键关系),但 django 的查询接口则不然。当字符串是“预期”时,您通常无法使用这种技术,因为您无法区分字符串值和应该进行评估的字符串。
In python, expressions are always evaluated eagerly. There is no lazy evaluation in python. Some libraries get around the absence of this useful feature by allowing values that should be of some specific type to instead be a string, which it later
eval
s. You can declare some parts of a django model this way (so that you can declare mutually referential foreign key relationships), but django's query interface does not. You wouldn't normally be able to use this kind of technique when a string is "expected", because you'd have no way to distinguish string values from strings that should beeval
ed.只有第一个是正确的:
我不明白懒惰/渴望与这个问题有什么关系。
Only the first one is correct:
I don't understand how lazy/eager is related to this question.
函数参数在调用函数之前进行评估:
当您创建字典时,所有内容都会在此时评估:
所以...
Function arguments are evaluated before the function is called:
When you create a dict everything is evaluated at that moment:
So...
我不确定这个问题是因为您好奇还是因为您想找到加载查询的方法。所以我会猜测:
我将使用 Q() 函数,也许将它们加载到 args 上,稍后使用 for 将它们设置在 Temp.objects.exclude 上,会是这样的:
其中查询是 Q( att.name = F('node_product_' + att.name)) 或更多 Q 对象。
如果您想查看的话,这里是文档。
在您询问信息之前,此查询不会执行,因此它是惰性的。我的意思是直到你做了类似的事情
I am not sure if this question is because you are curious or if you are trying to find ways to load querys. So I will take a guess:
I would be using the Q() function and maybe load them on args to later use a for to set them on the Temp.objects.exclude, would be something like this:
Where query is a Q(att.name = F('node_product_' + att.name)) or a lot more of Q objects.
Here is the documentation if you want to check it out.
This query will not execute until you ask for information, so it would be lazy. by that I mean until you do something like