为什么OrderedDict用camel大小写命名,而defaultdict是小写?

2024-10-08 21:21:15 发布

您现在位置:Python中文网/ 问答频道 /正文

看一下source code,似乎唯一的“原因”是OrderedDict是用Python编写的,而{}是用C编写的。但这似乎正在发生变化,因为python3.5应该有一个corderedect(请参见Python Bugs),这突出了我唯一的解释实际上是多么糟糕。在

有人能提供更好的解释吗?我希望有更好的理由。在

编辑alleged duplicate的答案对于python2.7是可以的,而对于没有类/类型区别的python3则不行。OrderedDict和{}都被解释器本身视为类:

>>> collections.defaultdict
<class 'collections.defaultdict'> 
>>> collections.OrderedDict
<class 'collections.OrderedDict'>

Tags: 答案编辑类型sourcecode原因collectionsclass
1条回答
网友
1楼 · 发布于 2024-10-08 21:21:15

根据我在python开发人员档案中发现的情况,这只是开发人员没有遵循自己的指导方针的一个例子。在

在讨论引入OrderedDict的政治公众人物时,Guido实际上建议renaming ^{} to ^{}来修复这种不一致性:

Anyway, it seems the collections module in particular is already internally inconsistent NamedTuple vs. defaultdict. In a sense defaultdict is the odd one out here, since these are things you import from some module, they're not built-in. Maybe it should be renamed to NamedDict?

请注意,NamedDict是一个打字错误,he meant ^{}

> I suppose you mean "DefaultDict".

Yes, I've been distracted. :-(

我不确定为什么这个更改(以及其他模块的类似更改,例如socket.socketdatetime.datetime)从未进行过,因为Guido支持这样做。在

具有讽刺意味的是,it was Guido(或者可能是Alex Martelli)想出了这个名字defaultdict,尽管他们是基于Google使用的一个名为DefaultDict的内部类:

Google has an internal data type called a DefaultDict which gets passed a default value upon construction. Its __getitem__ method, instead of raising KeyError, inserts a shallow copy (!) of the given default value into the dict when the value is not found.

...snip...

Over lunch with Alex Martelli, he proposed that a subclass of dict with this behavior (but implemented in C) would be a good addition to the language. It looks like it wouldn't be hard to implement. It could be a builtin named defaultdict. The first, required, argument to the constructor should be the default value. Remaining arguments (even keyword args) are passed unchanged to the dict constructor.

讨论很快从defaultdict变成了它是collections模块的一部分,但是所有小写的名称都被保留了。这个讨论发生在2006年,所以PEP8在那时已经存在很多年了。不知道为什么当时没有人想到它应该被命名为DefaultDict。在

相关问题 更多 >

    热门问题