比较 Python 中的闭包
我的目标是比较两个有界闭包,并检查它们是否以相同的输入参数 len
为界,
def foo(len: int):
def foob():
return len
return foob
a = foo(1)
b = foo(1)
print(a == b)
输出为 False。 但是,当我使用以下命令检查相等性时,
print(a.__closure__ == b.__closure__)
当输入参数 len 不同时,输出似乎为 True 和 False (正如我希望它工作的那样)。当我遍历此类函数闭包签名的大字典时,问题就出现了,其中检查的是 __eq__
而不是 __closure__
。有什么办法可以解决这个问题吗?
更新:问题不够清晰。 如果我要做这样的事情:
a_dict[foo(1)] = 0x12
即使 foo(1) 存在于字典中,它也会为 foo(1) 创建一个新的闭包对象,因为它使用 __eq__ 方法进行检查。
My goal is to compare two bounded closures and check if they are bounded with the same input argument len
def foo(len: int):
def foob():
return len
return foob
a = foo(1)
b = foo(1)
print(a == b)
The output is False.
But when I check for equality using the following,
print(a.__closure__ == b.__closure__)
the output appears to be True and False when the input argument len
is different (just as I want it to work). The problem comes when I am traversing through a large dictionary of such function closure signature where __eq__
is checked for instead of __closure__
. Is there any way to get around this?
UPDATE: There was a lack of clarity in the problem.
If I were to do something like this:
a_dict[foo(1)] = 0x12
It would create a new closure object for foo(1) even if foo(1) were present in the dictionary as it checks using __eq__
method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论