为什么在这种情况下使用str()?

Seo*_*eom 4 python django

这些是来自django.db.models.fields的代码

__all__ = [str(x) for x in (
    'AutoField', 'BLANK_CHOICE_DASH', 'BigAutoField', 'BigIntegerField',
    'BinaryField', 'BooleanField', 'CharField', 'CommaSeparatedIntegerField',
    'DateField', 'DateTimeField', 'DecimalField', 'DurationField',
    'EmailField', 'Empty', 'Field', 'FieldDoesNotExist', 'FilePathField',
    'FloatField', 'GenericIPAddressField', 'IPAddressField', 'IntegerField',
    'NOT_PROVIDED', 'NullBooleanField', 'PositiveIntegerField',
    'PositiveSmallIntegerField', 'SlugField', 'SmallIntegerField', 'TextField',
    'TimeField', 'URLField', 'UUIDField',
)]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我认为str(x) for x in (...)并且x for x in (...)是一样的.为什么使用str()?

tim*_*geb 7

请注意from __future__ import unicode_literals代码顶部的.现在默认情况下,每个字符串文字都是一个unicode字符串(就像它已经在Python 3中一样).

>>> from __future__ import unicode_literals
>>> s = 'test'
>>> type(s)
<type 'unicode'>
Run Code Online (Sandbox Code Playgroud)

为了避免TypeError在评论中提到

# Avoid "TypeError: Item in ``from list'' not a string" -- unicode_literals
# makes these strings unicode
Run Code Online (Sandbox Code Playgroud)

元组('AutoField', 'BLANK_CHOICE_DASH', ...)中的所有unicode文字都转换为Python 2字节串.

你是对的,如果import顶部的语句不在那里,列表理解将是完全没有意义的(在两个版本的Python中).