[英]How to visualize and understand this piece of code
I came across this code from https://quanttype.net/posts/2016-03-29-defaultdicts-all-the-way-down.html and I am not able to understand how or why this is working.我从https://quanttype.net/posts/2016-03-29-defaultdicts-all-the-way-down.html遇到了这段代码,我无法理解它是如何工作的或为什么工作的。 I would love to know how someone could visualize this and understand this
我很想知道有人如何想象并理解这一点
Running this inside a debugger did not yield an understanding在调试器中运行它并没有产生理解
def fix(f):
return lambda *args, **kwargs: f(fix(f), *args, **kwargs)
>>> from collections import defaultdict
>>> d = fix(defaultdict)()
>>> d["a"]["b"]["c"]
defaultdict(<function <lambda> at 0x105c4bed8>, {})
Let's consider a slightly simpler version of fix
:让我们考虑一个稍微简单的
fix
版本:
def fix(f):
return lambda: f(fix(f))
When we call fix(defaultdict)
, we of course get lambda: defaultdict(fix(defaultdict))
.当我们调用
fix(defaultdict)
时,我们当然会得到lambda: defaultdict(fix(defaultdict))
。 It will return a separate lambda
each time, but all of those lambda
functions have the same net effect.它每次都会返回一个单独的
lambda
,但所有这些lambda
函数具有相同的净效果。 When the first lambda
is called, it creates another one, and sets that as the factory for the defaultdict
that it returns.当第一个
lambda
被调用时,它会创建另一个,并将其设置为它返回的defaultdict
的工厂。
The defaultdict
that we get back, will use the lambda
to create default values.我们返回的
defaultdict
将使用lambda
创建默认值。 So when a key-value pair is inserted, the value will become another defaultdict, that has its own lambda, which can do the same thing.所以当插入一个键值对时,该值会变成另一个defaultdict,它有自己的lambda,它可以做同样的事情。
This lets us store keys as deep as we want without creating the sub-dicts first, because at each level the new layer will automatically be created if needed (and that layer is set up to create the next when needed, and so on).这让我们可以在不首先创建子字典的情况下将键存储到我们想要的深度,因为在每个级别上,如果需要,将自动创建新层(并且该层被设置为在需要时创建下一个层,依此类推)。
The fix
in the actual code just forwards additional parameters to the defaultdict
constructor.实际代码中的
fix
只是将附加参数转发给defaultdict
构造函数。 The sample code doesn't use that functionality, but it could be used to initialize the contents instead of assigning them one at a time (see the documentation for defaultdict
for more details).示例代码不使用该功能,但它可用于初始化内容,而不是一次分配一个内容(有关更多详细信息,请参阅
defaultdict
的文档)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.