为什么Django使用元组进行设置而不是列表?

2024-05-15 10:25:00 发布

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

引用this answer

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使用元组而不是列表进行设置呢?示例:

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

从语义上来说,这(以及所有其他设置)不是一个完美的列表大小写吗?在


Tags: djangoanswerfrom列表havethiscontribare
3条回答

这在Django 1.9中有所改变:

Default settings that were tuples are now lists

The default settings in django.conf.global_settings were a combination of lists and tuples. All settings that were formerly tuples are now lists.

https://docs.djangoproject.com/en/1.9/releases/1.9/#default-settings-that-were-tuples-are-now-lists

根据user1474837在这个问题上指向Django ticket的有用链接,很明显元组用于向后兼容从一开始就进行设置的方式,这是因为元组相信它们比列表快。(根据票务讨论中引用的数据,它们是,但只是很小的一部分。)

具体来说,Django docs过去常说:

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

在后面的讨论中,一位Django核心开发人员指出:

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.

注意原始文档中的“纯”一词,如果按面值表示设置是不可变的,这是使用元组的原因。另外请注意,在票证讨论中有人将设置称为“某种程度上”不可变的,所以甚至不清楚设置实际上是不可变的。在

注:关于利息,请注意票证决议以以下内容结尾:

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.

我认为部分原因是元组是只读的,这样更安全,更适合设置。在

相关问题 更多 >