Skip to content

Commit 86470b7

Browse files
committed
Merge pull request #3517 from thedrow/feature/set-and-dict-literals
Replaced all dict and set conversions from lists to dict and set literals
2 parents df025f3 + 2e178bc commit 86470b7

File tree

7 files changed

+44
-51
lines changed

7 files changed

+44
-51
lines changed

rest_framework/exceptions.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,10 @@ def _force_text_recursive(data):
3030
return ReturnList(ret, serializer=data.serializer)
3131
return data
3232
elif isinstance(data, dict):
33-
ret = dict([
34-
(key, _force_text_recursive(value))
33+
ret = {
34+
key: _force_text_recursive(value)
3535
for key, value in data.items()
36-
])
36+
}
3737
if isinstance(data, ReturnDict):
3838
return ReturnDict(ret, serializer=data.serializer)
3939
return data

rest_framework/fields.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -604,8 +604,8 @@ class BooleanField(Field):
604604
}
605605
default_empty_html = False
606606
initial = False
607-
TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True))
608-
FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False))
607+
TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True}
608+
FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False}
609609

610610
def __init__(self, **kwargs):
611611
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option. Use `NullBooleanField` instead.'
@@ -634,9 +634,9 @@ class NullBooleanField(Field):
634634
'invalid': _('"{input}" is not a valid boolean.')
635635
}
636636
initial = None
637-
TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True))
638-
FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False))
639-
NULL_VALUES = set(('n', 'N', 'null', 'Null', 'NULL', '', None))
637+
TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True}
638+
FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False}
639+
NULL_VALUES = {'n', 'N', 'null', 'Null', 'NULL', '', None}
640640

641641
def __init__(self, **kwargs):
642642
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
@@ -1241,9 +1241,9 @@ def __init__(self, choices, **kwargs):
12411241
# Map the string representation of choices to the underlying value.
12421242
# Allows us to deal with eg. integer choices while supporting either
12431243
# integer or string input, but still get the correct datatype out.
1244-
self.choice_strings_to_values = dict([
1245-
(six.text_type(key), key) for key in self.choices.keys()
1246-
])
1244+
self.choice_strings_to_values = {
1245+
six.text_type(key): key for key in self.choices.keys()
1246+
}
12471247

12481248
self.allow_blank = kwargs.pop('allow_blank', False)
12491249

@@ -1302,15 +1302,15 @@ def to_internal_value(self, data):
13021302
if not self.allow_empty and len(data) == 0:
13031303
self.fail('empty')
13041304

1305-
return set([
1305+
return {
13061306
super(MultipleChoiceField, self).to_internal_value(item)
13071307
for item in data
1308-
])
1308+
}
13091309

13101310
def to_representation(self, value):
1311-
return set([
1311+
return {
13121312
self.choice_strings_to_values.get(six.text_type(item), item) for item in value
1313-
])
1313+
}
13141314

13151315

13161316
class FilePathField(ChoiceField):
@@ -1508,19 +1508,19 @@ def to_internal_value(self, data):
15081508
data = html.parse_html_dict(data)
15091509
if not isinstance(data, dict):
15101510
self.fail('not_a_dict', input_type=type(data).__name__)
1511-
return dict([
1512-
(six.text_type(key), self.child.run_validation(value))
1511+
return {
1512+
six.text_type(key): self.child.run_validation(value)
15131513
for key, value in data.items()
1514-
])
1514+
}
15151515

15161516
def to_representation(self, value):
15171517
"""
15181518
List of object instances -> List of dicts of primitive datatypes.
15191519
"""
1520-
return dict([
1521-
(six.text_type(key), self.child.to_representation(val))
1520+
return {
1521+
six.text_type(key): self.child.to_representation(val)
15221522
for key, val in value.items()
1523-
])
1523+
}
15241524

15251525

15261526
class JSONField(Field):

rest_framework/metadata.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def determine_actions(self, request, view):
7777
the fields that are accepted for 'PUT' and 'POST' methods.
7878
"""
7979
actions = {}
80-
for method in set(['PUT', 'POST']) & set(view.allowed_methods):
80+
for method in {'PUT', 'POST'} & set(view.allowed_methods):
8181
view.request = clone_request(request, method)
8282
try:
8383
# Test global permissions

rest_framework/pagination.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,7 @@ def _get_displayed_page_numbers(current, final):
7979

8080
# We always include the first two pages, last two pages, and
8181
# two pages either side of the current page.
82-
included = set((
83-
1,
84-
current - 1, current, current + 1,
85-
final
86-
))
82+
included = {1, current - 1, current, current + 1, final}
8783

8884
# If the break would only exclude a single page number then we
8985
# may as well include the page number instead of the break.

rest_framework/routers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ def _get_dynamic_routes(route, dynamic_routes):
174174
url_path = initkwargs.pop("url_path", None) or methodname
175175
ret.append(Route(
176176
url=replace_methodname(route.url, url_path),
177-
mapping=dict((httpmethod, methodname) for httpmethod in httpmethods),
177+
mapping={httpmethod: methodname for httpmethod in httpmethods},
178178
name=replace_methodname(route.name, url_path),
179179
initkwargs=initkwargs,
180180
))

rest_framework/serializers.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -125,10 +125,10 @@ def many_init(cls, *args, **kwargs):
125125
}
126126
if allow_empty is not None:
127127
list_kwargs['allow_empty'] = allow_empty
128-
list_kwargs.update(dict([
129-
(key, value) for key, value in kwargs.items()
128+
list_kwargs.update({
129+
key: value for key, value in kwargs.items()
130130
if key in LIST_SERIALIZER_KWARGS
131-
]))
131+
})
132132
meta = getattr(cls, 'Meta', None)
133133
list_serializer_class = getattr(meta, 'list_serializer_class', ListSerializer)
134134
return list_serializer_class(*args, **list_kwargs)
@@ -305,10 +305,10 @@ def get_validation_error_detail(exc):
305305
elif isinstance(exc.detail, dict):
306306
# If errors may be a dict we use the standard {key: list of values}.
307307
# Here we ensure that all the values are *lists* of errors.
308-
return dict([
309-
(key, value if isinstance(value, list) else [value])
308+
return {
309+
key: value if isinstance(value, list) else [value]
310310
for key, value in exc.detail.items()
311-
])
311+
}
312312
elif isinstance(exc.detail, list):
313313
# Errors raised as a list are non-field errors.
314314
return {
@@ -1237,13 +1237,10 @@ def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs
12371237

12381238
for model_field in model_fields.values():
12391239
# Include each of the `unique_for_*` field names.
1240-
unique_constraint_names |= set([
1241-
model_field.unique_for_date,
1242-
model_field.unique_for_month,
1243-
model_field.unique_for_year
1244-
])
1240+
unique_constraint_names |= {model_field.unique_for_date, model_field.unique_for_month,
1241+
model_field.unique_for_year}
12451242

1246-
unique_constraint_names -= set([None])
1243+
unique_constraint_names -= {None}
12471244

12481245
# Include each of the `unique_together` field names,
12491246
# so long as all the field names are included on the serializer.
@@ -1357,10 +1354,10 @@ def get_unique_together_validators(self):
13571354
# which may map onto a model field. Any dotted field name lookups
13581355
# cannot map to a field, and must be a traversal, so we're not
13591356
# including those.
1360-
field_names = set([
1357+
field_names = {
13611358
field.source for field in self.fields.values()
13621359
if (field.source != '*') and ('.' not in field.source)
1363-
])
1360+
}
13641361

13651362
# Note that we make sure to check `unique_together` both on the
13661363
# base model class, but also on any parent classes.

rest_framework/validators.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,11 @@ def enforce_required_fields(self, attrs):
100100
if self.instance is not None:
101101
return
102102

103-
missing = dict([
104-
(field_name, self.missing_message)
103+
missing = {
104+
field_name: self.missing_message
105105
for field_name in self.fields
106106
if field_name not in attrs
107-
])
107+
}
108108
if missing:
109109
raise ValidationError(missing)
110110

@@ -120,10 +120,10 @@ def filter_queryset(self, attrs, queryset):
120120
attrs[field_name] = getattr(self.instance, field_name)
121121

122122
# Determine the filter keyword arguments and filter the queryset.
123-
filter_kwargs = dict([
124-
(field_name, attrs[field_name])
123+
filter_kwargs = {
124+
field_name: attrs[field_name]
125125
for field_name in self.fields
126-
])
126+
}
127127
return queryset.filter(**filter_kwargs)
128128

129129
def exclude_current_instance(self, attrs, queryset):
@@ -184,11 +184,11 @@ def enforce_required_fields(self, attrs):
184184
The `UniqueFor<Range>Validator` classes always force an implied
185185
'required' state on the fields they are applied to.
186186
"""
187-
missing = dict([
188-
(field_name, self.missing_message)
187+
missing = {
188+
field_name: self.missing_message
189189
for field_name in [self.field, self.date_field]
190190
if field_name not in attrs
191-
])
191+
}
192192
if missing:
193193
raise ValidationError(missing)
194194

0 commit comments

Comments
 (0)