SeokJun Yeom
SeokJun Yeom

Reputation: 551

Why is the 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 (...) are the same in this situation. Why is the str() used?

Upvotes: 4

Views: 111

Answers (1)

timgeb
timgeb

Reputation: 78780

Note the from __future__ import unicode_literals at the top of the code. Every string literal will be a unicode string by default now (like it is already in Python 3).

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

In order to avoid the TypeError mentioned in the comment

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

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

You are right that the list comprehension would be completely pointless (in both versions of Python) if the import statement at the top was not there.

Upvotes: 7

Related Questions