Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the str() used in this situation?

Tags:

python

django

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?

like image 969
SeokJun Yeom Avatar asked Mar 10 '23 03:03

SeokJun Yeom


1 Answers

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.

like image 143
timgeb Avatar answered Mar 20 '23 13:03

timgeb