Why is str () used in this situation?

These are the codes from 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',
)]

I think str(x) for x in (...), and x for x in (...)in this situation the same. Why is str () used?

+4
source share
1 answer

Pay attention to from __future__ import unicode_literalsthe top of the code. Each string literal will by default be a unicode string (for example, it is already in Python 3).

>>> from __future__ import unicode_literals
>>> s = 'test'
>>> type(s)
<type 'unicode'>

To avoid TypeErrormentioned in the comment

# Avoid "TypeError: Item in ``from list'' not a string" -- unicode_literals
# makes these strings unicode

all unicode literals in a tuple are ('AutoField', 'BLANK_CHOICE_DASH', ...)converted to Python 2 bytes.

You are right that list comprehension would be completely meaningless (in both versions of Python) if the statement importabove was not there.

+7

Source: https://habr.com/ru/post/1676591/


All Articles