python - kwargs.copy() 的插入顺序现在也应该被认为是有保证的吗? (发布 Python 3.6)

标签 python python-3.6

关键字参数的插入顺序现在是 guaranteed to be preserved在 3.6 版本的 Python 中。通过更改 dict 的基础表示,这已成为可能。目的。

但是,有人指出 - somewhat strenuously - dict 的顺序保存到目前为止,一般不应依赖该对象。文档以这种方式解释了这种情况:

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

PEP 468没有提及有关复制关键字参数的任何内容。但有时人们可能希望遍历 kwargs 的副本。参数(例如,在 for 循环中改变 kwargs 时):

def i_will_never_fail(**kwargs):
    for thing1,thing2 in zip(kwargs.copy(), kwargs):
        assert thing1==thing2

我的问题是:对象的顺序应该由 kwargs.copy() 产生吗?也被认为是有保障的?或者这也应该被视为一个实现细节?是 OrderedDict only mostly dead

最佳答案

答案将取决于实现。

假设 CPython 非常流行,答案是肯定的。从 dictobject.c 中的 PyDict_Copy 函数(第 2615 行)可以看出代码,随着对值的引用的增加,函数开始复制

split_copy->ma_keys = mp->ma_keys;

这,在 mp 被分配了字典对象之后(或者更准确地说,将原始 dict 显式转换为 PyDictObject) .

由于键保留了它们的顺序,并且考虑到当前的存储形式(如 Jim's explanation here 中所示),生成的字典应该以相同的方式排序。

Again, that is currently considered an implementation detail and you should not make any of your code depend on it.

关于python - kwargs.copy() 的插入顺序现在也应该被认为是有保证的吗? (发布 Python 3.6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44162165/

相关文章:

python - 未绑定(bind)本地错误: local variable 'classes_taken' referenced before assignment

python - a def 在函数中的用法是什么?

python - 无法解析使用 latin-1 编码的文件

python 全局命名空间不可访问

python - Django 中的查询集联合

python - 如何根据错误值找到两个 pandas 系列之间的交集

python - py-datatable 'in' 运算符?

python - 如何使用 lambda 在 for 循环内创建 if ?

python - 当 header 是动态的时,避免将批量数据导出到 csv

python - 移动光标线位置 QTextEdit