为什么Django使用元组进行设置而不是列表? [英] Why does Django use tuples for settings and not lists?

查看:288
本文介绍了为什么Django使用元组进行设置而不是列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用此答案

除了元组是不可变的,还有一个语义上的区别,可以指导他们的使用。元组是异构数据结构(即它们的条目具有不同的含义),而列表是同构序列。元组有结构,列表有顺序。
Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.

这对我有意义。但是为什么Django使用元组而不是列表进行设置?示例:

This makes sense to me. But why does Django use tuples and not lists for settings? Example:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

这不是(和所有其他设置)完美的语法语义一个列表?

Isn't this (and all the other settings) a perfect case semantically for a list?

推荐答案

根据user1474837的有用链接到 Django ticket 在这个问题上,似乎很明显,元组用于向后兼容,从一开始就设置完成的方式,这是由于这些元组是由于他们的信念比列表快。 (他们是,但只是非常轻微,根据机票讨论中引用的数据。)

Based on user1474837's helpful link to the Django ticket on this question, it seems clear that tuples are used for backwards compatibility with the way settings were done from the start, which was with tuples due to the belief they were faster than lists. (They are, but only very slightly, according to data cited in the ticket discussion.)

具体来说,Django文档曾经说:

Specifically, Django docs used to say:


对于作为序列的设置,请使用元组而不是列表。这完全是为了表演。

For settings that are sequences, use tuples instead of lists. This is purely for performance.

在讨论之后,Django核心开发人员注意到:

Later in the discussion, a Django core developer notes:


我们当然不会将元组从列表移到列表中,因为它会破坏已经预料到事物成为元组的现有代码。然而,我将删除性能说明,因为它不值得吓人。

We're certainly not about to move from tuples to lists there because it would break existing code that already expects things to be tuples. I'll remove the performance note, however, since it's not worth scaring people.

请注意原始文档中的纯粹一词 - 如果以面值取得意味着指示设置是不可变的,则不是使用元组的原因。还要注意,票证讨论中的某些人将参考设置引用为不可改变,所以甚至不清楚设置实际上是不可变的。

Note the word "purely" in the original documentation -- which if taken at face value would mean indicating settings are immutable is not a reason tuples are used. Also note someone in the ticket discussion references settings as "sort of" immutable, so it's not even clear settings are in fact immutable.

为了感兴趣,请注意票解决方案以:

P.S. For interest, note the ticket resolution ends with:


更改了编写自己的设置建议,提到Django
使用元组,但不是推荐。这可能会导致无休止的
元组与列表辩论。

Changed the "write your own settings" recommendation to mention that Django uses tuples, but not making it a recommendation. That might head off the endless tuples vs. lists debates.

这篇关于为什么Django使用元组进行设置而不是列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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