Use dict and set literals instead of calls to dict() and set() (#5559)

Set literals are available on all supported Python versions. They are
idiomatic and always faster:

$ python3 -m timeit '{}'
10000000 loops, best of 3: 0.0357 usec per loop
$ python3 -m timeit 'dict()'
10000000 loops, best of 3: 0.104 usec per loop

$ python3 -m timeit '{1, 2, 3}'
10000000 loops, best of 3: 0.0754 usec per loop
$ python3 -m timeit 'set([1, 2, 3])'
1000000 loops, best of 3: 0.228 usec per loop
This commit is contained in:
Jon Dufresne 2017-11-06 01:03:01 -08:00 committed by Carlton Gibson
parent f77e794dc8
commit 0552810410
9 changed files with 16 additions and 16 deletions

View File

@ -46,7 +46,7 @@ def api_view(http_method_names=None, exclude_from_schema=False):
assert isinstance(http_method_names, (list, tuple)), \
'@api_view expected a list of strings, received %s' % type(http_method_names).__name__
allowed_methods = set(http_method_names) | set(('options',))
allowed_methods = set(http_method_names) | {'options'}
WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods]
def handler(self, *args, **kwargs):

View File

@ -118,9 +118,9 @@ def distribute_links(obj):
def is_custom_action(action):
return action not in set([
return action not in {
'retrieve', 'list', 'create', 'update', 'partial_update', 'destroy'
])
}
def endpoint_ordering(endpoint):

View File

@ -385,11 +385,11 @@ class AutoSchema(ViewInspector):
view = self.view
# Core API supports the following request encodings over HTTP...
supported_media_types = set((
supported_media_types = {
'application/json',
'application/x-www-form-urlencoded',
'multipart/form-data',
))
}
parser_classes = getattr(view, 'parser_classes', [])
for parser_class in parser_classes:
media_type = getattr(parser_class, 'media_type', None)

View File

@ -1172,13 +1172,13 @@ class ModelSerializer(Serializer):
# Some model fields may introduce kwargs that would not be valid
# for the choice field. We need to strip these out.
# Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES)
valid_kwargs = set((
valid_kwargs = {
'read_only', 'write_only',
'required', 'default', 'initial', 'source',
'label', 'help_text', 'style',
'error_messages', 'validators', 'allow_null', 'allow_blank',
'choices'
))
}
for key in list(field_kwargs.keys()):
if key not in valid_kwargs:
field_kwargs.pop(key)

View File

@ -1618,15 +1618,15 @@ class TestMultipleChoiceField(FieldValues):
"""
valid_inputs = {
(): set(),
('aircon',): set(['aircon']),
('aircon', 'manual'): set(['aircon', 'manual']),
('aircon',): {'aircon'},
('aircon', 'manual'): {'aircon', 'manual'},
}
invalid_inputs = {
'abc': ['Expected a list of items but got type "str".'],
('aircon', 'incorrect'): ['"incorrect" is not a valid choice.']
}
outputs = [
(['aircon', 'manual', 'incorrect'], set(['aircon', 'manual', 'incorrect']))
(['aircon', 'manual', 'incorrect'], {'aircon', 'manual', 'incorrect'})
]
field = serializers.MultipleChoiceField(
choices=[

View File

@ -44,7 +44,7 @@ class InheritedModelSerializationTests(TestCase):
"""
child = ChildModel(name1='parent name', name2='child name')
serializer = DerivedModelSerializer(child)
assert set(serializer.data.keys()) == set(['name1', 'name2', 'id'])
assert set(serializer.data.keys()) == {'name1', 'name2', 'id'}
def test_onetoone_primary_key_model_fields_as_expected(self):
"""
@ -54,7 +54,7 @@ class InheritedModelSerializationTests(TestCase):
parent = ParentModel.objects.create(name1='parent name')
associate = AssociatedModel.objects.create(name='hello', ref=parent)
serializer = AssociatedModelSerializer(associate)
assert set(serializer.data.keys()) == set(['name', 'ref'])
assert set(serializer.data.keys()) == {'name', 'ref'}
def test_data_is_valid_without_parent_ptr(self):
"""

View File

@ -41,4 +41,4 @@ class InheritedModelSerializationTests(TestCase):
child = ChildModel(name1='parent name', name2='child name')
serializer = DerivedModelSerializer(child)
self.assertEqual(set(serializer.data.keys()),
set(['name1', 'name2', 'id', 'childassociatedmodel']))
{'name1', 'name2', 'id', 'childassociatedmodel'})

View File

@ -316,7 +316,7 @@ class JSONRendererTests(TestCase):
def test_render_dict_abc_obj(self):
class Dict(MutableMapping):
def __init__(self):
self._dict = dict()
self._dict = {}
def __getitem__(self, key):
return self._dict.__getitem__(key)

View File

@ -194,11 +194,11 @@ class TestNestedSerializerWithList:
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
assert serializer.validated_data['nested']['example'] == set([1, 2])
assert serializer.validated_data['nested']['example'] == {1, 2}
def test_nested_serializer_with_list_multipart(self):
input_data = QueryDict('nested.example=1&nested.example=2')
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
assert serializer.validated_data['nested']['example'] == set([1, 2])
assert serializer.validated_data['nested']['example'] == {1, 2}