Replaced all dict and set conversions from lists to dict and set literals.

This commit is contained in:
Omer Katz 2015-10-17 12:00:11 +03:00
parent df025f3d98
commit 2e178bc970
7 changed files with 44 additions and 51 deletions

View File

@ -30,10 +30,10 @@ def _force_text_recursive(data):
return ReturnList(ret, serializer=data.serializer)
return data
elif isinstance(data, dict):
ret = dict([
(key, _force_text_recursive(value))
ret = {
key: _force_text_recursive(value)
for key, value in data.items()
])
}
if isinstance(data, ReturnDict):
return ReturnDict(ret, serializer=data.serializer)
return data

View File

@ -604,8 +604,8 @@ class BooleanField(Field):
}
default_empty_html = False
initial = False
TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True))
FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False))
TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True}
FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False}
def __init__(self, **kwargs):
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option. Use `NullBooleanField` instead.'
@ -634,9 +634,9 @@ class NullBooleanField(Field):
'invalid': _('"{input}" is not a valid boolean.')
}
initial = None
TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True))
FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False))
NULL_VALUES = set(('n', 'N', 'null', 'Null', 'NULL', '', None))
TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True}
FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False}
NULL_VALUES = {'n', 'N', 'null', 'Null', 'NULL', '', None}
def __init__(self, **kwargs):
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
@ -1241,9 +1241,9 @@ class ChoiceField(Field):
# Map the string representation of choices to the underlying value.
# Allows us to deal with eg. integer choices while supporting either
# integer or string input, but still get the correct datatype out.
self.choice_strings_to_values = dict([
(six.text_type(key), key) for key in self.choices.keys()
])
self.choice_strings_to_values = {
six.text_type(key): key for key in self.choices.keys()
}
self.allow_blank = kwargs.pop('allow_blank', False)
@ -1302,15 +1302,15 @@ class MultipleChoiceField(ChoiceField):
if not self.allow_empty and len(data) == 0:
self.fail('empty')
return set([
return {
super(MultipleChoiceField, self).to_internal_value(item)
for item in data
])
}
def to_representation(self, value):
return set([
return {
self.choice_strings_to_values.get(six.text_type(item), item) for item in value
])
}
class FilePathField(ChoiceField):
@ -1508,19 +1508,19 @@ class DictField(Field):
data = html.parse_html_dict(data)
if not isinstance(data, dict):
self.fail('not_a_dict', input_type=type(data).__name__)
return dict([
(six.text_type(key), self.child.run_validation(value))
return {
six.text_type(key): self.child.run_validation(value)
for key, value in data.items()
])
}
def to_representation(self, value):
"""
List of object instances -> List of dicts of primitive datatypes.
"""
return dict([
(six.text_type(key), self.child.to_representation(val))
return {
six.text_type(key): self.child.to_representation(val)
for key, val in value.items()
])
}
class JSONField(Field):

View File

@ -77,7 +77,7 @@ class SimpleMetadata(BaseMetadata):
the fields that are accepted for 'PUT' and 'POST' methods.
"""
actions = {}
for method in set(['PUT', 'POST']) & set(view.allowed_methods):
for method in {'PUT', 'POST'} & set(view.allowed_methods):
view.request = clone_request(request, method)
try:
# Test global permissions

View File

@ -79,11 +79,7 @@ def _get_displayed_page_numbers(current, final):
# We always include the first two pages, last two pages, and
# two pages either side of the current page.
included = set((
1,
current - 1, current, current + 1,
final
))
included = {1, current - 1, current, current + 1, final}
# If the break would only exclude a single page number then we
# may as well include the page number instead of the break.

View File

@ -174,7 +174,7 @@ class SimpleRouter(BaseRouter):
url_path = initkwargs.pop("url_path", None) or methodname
ret.append(Route(
url=replace_methodname(route.url, url_path),
mapping=dict((httpmethod, methodname) for httpmethod in httpmethods),
mapping={httpmethod: methodname for httpmethod in httpmethods},
name=replace_methodname(route.name, url_path),
initkwargs=initkwargs,
))

View File

@ -125,10 +125,10 @@ class BaseSerializer(Field):
}
if allow_empty is not None:
list_kwargs['allow_empty'] = allow_empty
list_kwargs.update(dict([
(key, value) for key, value in kwargs.items()
list_kwargs.update({
key: value for key, value in kwargs.items()
if key in LIST_SERIALIZER_KWARGS
]))
})
meta = getattr(cls, 'Meta', None)
list_serializer_class = getattr(meta, 'list_serializer_class', ListSerializer)
return list_serializer_class(*args, **list_kwargs)
@ -305,10 +305,10 @@ def get_validation_error_detail(exc):
elif isinstance(exc.detail, dict):
# If errors may be a dict we use the standard {key: list of values}.
# Here we ensure that all the values are *lists* of errors.
return dict([
(key, value if isinstance(value, list) else [value])
return {
key: value if isinstance(value, list) else [value]
for key, value in exc.detail.items()
])
}
elif isinstance(exc.detail, list):
# Errors raised as a list are non-field errors.
return {
@ -1237,13 +1237,10 @@ class ModelSerializer(Serializer):
for model_field in model_fields.values():
# Include each of the `unique_for_*` field names.
unique_constraint_names |= set([
model_field.unique_for_date,
model_field.unique_for_month,
model_field.unique_for_year
])
unique_constraint_names |= {model_field.unique_for_date, model_field.unique_for_month,
model_field.unique_for_year}
unique_constraint_names -= set([None])
unique_constraint_names -= {None}
# Include each of the `unique_together` field names,
# so long as all the field names are included on the serializer.
@ -1357,10 +1354,10 @@ class ModelSerializer(Serializer):
# which may map onto a model field. Any dotted field name lookups
# cannot map to a field, and must be a traversal, so we're not
# including those.
field_names = set([
field_names = {
field.source for field in self.fields.values()
if (field.source != '*') and ('.' not in field.source)
])
}
# Note that we make sure to check `unique_together` both on the
# base model class, but also on any parent classes.

View File

@ -100,11 +100,11 @@ class UniqueTogetherValidator(object):
if self.instance is not None:
return
missing = dict([
(field_name, self.missing_message)
missing = {
field_name: self.missing_message
for field_name in self.fields
if field_name not in attrs
])
}
if missing:
raise ValidationError(missing)
@ -120,10 +120,10 @@ class UniqueTogetherValidator(object):
attrs[field_name] = getattr(self.instance, field_name)
# Determine the filter keyword arguments and filter the queryset.
filter_kwargs = dict([
(field_name, attrs[field_name])
filter_kwargs = {
field_name: attrs[field_name]
for field_name in self.fields
])
}
return queryset.filter(**filter_kwargs)
def exclude_current_instance(self, attrs, queryset):
@ -184,11 +184,11 @@ class BaseUniqueForValidator(object):
The `UniqueFor<Range>Validator` classes always force an implied
'required' state on the fields they are applied to.
"""
missing = dict([
(field_name, self.missing_message)
missing = {
field_name: self.missing_message
for field_name in [self.field, self.date_field]
if field_name not in attrs
])
}
if missing:
raise ValidationError(missing)