Skip to content

Commit

Permalink
Merge pull request #3517 from thedrow/feature/set-and-dict-literals
Browse files Browse the repository at this point in the history
Replaced all dict and set conversions from lists to dict and set literals
  • Loading branch information
tomchristie committed Oct 19, 2015
2 parents df025f3 + 2e178bc commit 86470b7
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 51 deletions.
6 changes: 3 additions & 3 deletions rest_framework/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 18 additions & 18 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.'
Expand Down Expand Up @@ -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.'
Expand Down Expand Up @@ -1241,9 +1241,9 @@ def __init__(self, choices, **kwargs):
# 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)

Expand Down Expand Up @@ -1302,15 +1302,15 @@ def to_internal_value(self, data):
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):
Expand Down Expand Up @@ -1508,19 +1508,19 @@ def to_internal_value(self, data):
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):
Expand Down
2 changes: 1 addition & 1 deletion rest_framework/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def determine_actions(self, request, view):
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
Expand Down
6 changes: 1 addition & 5 deletions rest_framework/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion rest_framework/routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def _get_dynamic_routes(route, dynamic_routes):
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,
))
Expand Down
25 changes: 11 additions & 14 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,10 @@ def many_init(cls, *args, **kwargs):
}
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)
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -1237,13 +1237,10 @@ def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs

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.
Expand Down Expand Up @@ -1357,10 +1354,10 @@ def get_unique_together_validators(self):
# 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.
Expand Down
18 changes: 9 additions & 9 deletions rest_framework/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ def enforce_required_fields(self, attrs):
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)

Expand All @@ -120,10 +120,10 @@ def filter_queryset(self, attrs, queryset):
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):
Expand Down Expand Up @@ -184,11 +184,11 @@ def enforce_required_fields(self, attrs):
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)

Expand Down

0 comments on commit 86470b7

Please sign in to comment.