如何使defaultdict对不期望的客户安全? [英] How do I make a defaultdict safe for unexpecting clients?

查看:68
本文介绍了如何使defaultdict对不期望的客户安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几次(甚至连续几次)都被defaultdict错误咬住了:忘记实际上是defaultdict并将其像普通词典一样对待。

Several times (even several in a row) I've been bitten by the defaultdict bug: forgetting that something is actually a defaultdict and treating it like a regular dictionary.

d = defaultdict(list)

...

try:
  v = d["key"]
except KeyError:
  print "Sorry, no dice!"

对于那些也被咬过的人来说,问题显而易见:当d没有关键的关键时, v = d [ key] 神奇地创建一个空列表并将其分配给两个 d [ key] v 而不是引发异常。如果d来自某个模块,而该模块的详细信息人们可能不太记得,那将是很难找到的。

For those who have been bitten too, the problem is evident: when d has no key 'key', the v = d["key"] magically creates an empty list and assigns it to both d["key"] and v instead of raising an exception. Which can be quite a pain to track down if d comes from some module whose details one doesn't remember very well.

我正在寻找一种方法来获取摆脱这个错误。对我而言,最好的解决方案是在将defaultdict的魔术返回给客户端之前以某种方式禁用它。

I'm looking for a way to take the sting out of this bug. For me, the best solution would be to somehow disable a defaultdict's magic before returning it to the client.

推荐答案

您可以阻止创建通过分配 d.default_factory = None 设置默认值。但是,我不太喜欢对象突然改变行为的想法。我希望将值复制到新的 dict ,除非这样做会严重影响性能。

You can prevent creation of default values by assigning d.default_factory = None. However, I don't quite like the idea of object suddenly changing behavior. I'd prefer copying values to the new dict unless it imposes severe performance penalty.

这篇关于如何使defaultdict对不期望的客户安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆