mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-22 17:47:04 +03:00
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:
parent
f77e794dc8
commit
0552810410
|
@ -46,7 +46,7 @@ def api_view(http_method_names=None, exclude_from_schema=False):
|
||||||
assert isinstance(http_method_names, (list, tuple)), \
|
assert isinstance(http_method_names, (list, tuple)), \
|
||||||
'@api_view expected a list of strings, received %s' % type(http_method_names).__name__
|
'@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]
|
WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods]
|
||||||
|
|
||||||
def handler(self, *args, **kwargs):
|
def handler(self, *args, **kwargs):
|
||||||
|
|
|
@ -118,9 +118,9 @@ def distribute_links(obj):
|
||||||
|
|
||||||
|
|
||||||
def is_custom_action(action):
|
def is_custom_action(action):
|
||||||
return action not in set([
|
return action not in {
|
||||||
'retrieve', 'list', 'create', 'update', 'partial_update', 'destroy'
|
'retrieve', 'list', 'create', 'update', 'partial_update', 'destroy'
|
||||||
])
|
}
|
||||||
|
|
||||||
|
|
||||||
def endpoint_ordering(endpoint):
|
def endpoint_ordering(endpoint):
|
||||||
|
|
|
@ -385,11 +385,11 @@ class AutoSchema(ViewInspector):
|
||||||
view = self.view
|
view = self.view
|
||||||
|
|
||||||
# Core API supports the following request encodings over HTTP...
|
# Core API supports the following request encodings over HTTP...
|
||||||
supported_media_types = set((
|
supported_media_types = {
|
||||||
'application/json',
|
'application/json',
|
||||||
'application/x-www-form-urlencoded',
|
'application/x-www-form-urlencoded',
|
||||||
'multipart/form-data',
|
'multipart/form-data',
|
||||||
))
|
}
|
||||||
parser_classes = getattr(view, 'parser_classes', [])
|
parser_classes = getattr(view, 'parser_classes', [])
|
||||||
for parser_class in parser_classes:
|
for parser_class in parser_classes:
|
||||||
media_type = getattr(parser_class, 'media_type', None)
|
media_type = getattr(parser_class, 'media_type', None)
|
||||||
|
|
|
@ -1172,13 +1172,13 @@ class ModelSerializer(Serializer):
|
||||||
# Some model fields may introduce kwargs that would not be valid
|
# Some model fields may introduce kwargs that would not be valid
|
||||||
# for the choice field. We need to strip these out.
|
# for the choice field. We need to strip these out.
|
||||||
# Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES)
|
# Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES)
|
||||||
valid_kwargs = set((
|
valid_kwargs = {
|
||||||
'read_only', 'write_only',
|
'read_only', 'write_only',
|
||||||
'required', 'default', 'initial', 'source',
|
'required', 'default', 'initial', 'source',
|
||||||
'label', 'help_text', 'style',
|
'label', 'help_text', 'style',
|
||||||
'error_messages', 'validators', 'allow_null', 'allow_blank',
|
'error_messages', 'validators', 'allow_null', 'allow_blank',
|
||||||
'choices'
|
'choices'
|
||||||
))
|
}
|
||||||
for key in list(field_kwargs.keys()):
|
for key in list(field_kwargs.keys()):
|
||||||
if key not in valid_kwargs:
|
if key not in valid_kwargs:
|
||||||
field_kwargs.pop(key)
|
field_kwargs.pop(key)
|
||||||
|
|
|
@ -1618,15 +1618,15 @@ class TestMultipleChoiceField(FieldValues):
|
||||||
"""
|
"""
|
||||||
valid_inputs = {
|
valid_inputs = {
|
||||||
(): set(),
|
(): set(),
|
||||||
('aircon',): set(['aircon']),
|
('aircon',): {'aircon'},
|
||||||
('aircon', 'manual'): set(['aircon', 'manual']),
|
('aircon', 'manual'): {'aircon', 'manual'},
|
||||||
}
|
}
|
||||||
invalid_inputs = {
|
invalid_inputs = {
|
||||||
'abc': ['Expected a list of items but got type "str".'],
|
'abc': ['Expected a list of items but got type "str".'],
|
||||||
('aircon', 'incorrect'): ['"incorrect" is not a valid choice.']
|
('aircon', 'incorrect'): ['"incorrect" is not a valid choice.']
|
||||||
}
|
}
|
||||||
outputs = [
|
outputs = [
|
||||||
(['aircon', 'manual', 'incorrect'], set(['aircon', 'manual', 'incorrect']))
|
(['aircon', 'manual', 'incorrect'], {'aircon', 'manual', 'incorrect'})
|
||||||
]
|
]
|
||||||
field = serializers.MultipleChoiceField(
|
field = serializers.MultipleChoiceField(
|
||||||
choices=[
|
choices=[
|
||||||
|
|
|
@ -44,7 +44,7 @@ class InheritedModelSerializationTests(TestCase):
|
||||||
"""
|
"""
|
||||||
child = ChildModel(name1='parent name', name2='child name')
|
child = ChildModel(name1='parent name', name2='child name')
|
||||||
serializer = DerivedModelSerializer(child)
|
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):
|
def test_onetoone_primary_key_model_fields_as_expected(self):
|
||||||
"""
|
"""
|
||||||
|
@ -54,7 +54,7 @@ class InheritedModelSerializationTests(TestCase):
|
||||||
parent = ParentModel.objects.create(name1='parent name')
|
parent = ParentModel.objects.create(name1='parent name')
|
||||||
associate = AssociatedModel.objects.create(name='hello', ref=parent)
|
associate = AssociatedModel.objects.create(name='hello', ref=parent)
|
||||||
serializer = AssociatedModelSerializer(associate)
|
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):
|
def test_data_is_valid_without_parent_ptr(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -41,4 +41,4 @@ class InheritedModelSerializationTests(TestCase):
|
||||||
child = ChildModel(name1='parent name', name2='child name')
|
child = ChildModel(name1='parent name', name2='child name')
|
||||||
serializer = DerivedModelSerializer(child)
|
serializer = DerivedModelSerializer(child)
|
||||||
self.assertEqual(set(serializer.data.keys()),
|
self.assertEqual(set(serializer.data.keys()),
|
||||||
set(['name1', 'name2', 'id', 'childassociatedmodel']))
|
{'name1', 'name2', 'id', 'childassociatedmodel'})
|
||||||
|
|
|
@ -316,7 +316,7 @@ class JSONRendererTests(TestCase):
|
||||||
def test_render_dict_abc_obj(self):
|
def test_render_dict_abc_obj(self):
|
||||||
class Dict(MutableMapping):
|
class Dict(MutableMapping):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._dict = dict()
|
self._dict = {}
|
||||||
|
|
||||||
def __getitem__(self, key):
|
def __getitem__(self, key):
|
||||||
return self._dict.__getitem__(key)
|
return self._dict.__getitem__(key)
|
||||||
|
|
|
@ -194,11 +194,11 @@ class TestNestedSerializerWithList:
|
||||||
serializer = self.Serializer(data=input_data)
|
serializer = self.Serializer(data=input_data)
|
||||||
|
|
||||||
assert serializer.is_valid()
|
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):
|
def test_nested_serializer_with_list_multipart(self):
|
||||||
input_data = QueryDict('nested.example=1&nested.example=2')
|
input_data = QueryDict('nested.example=1&nested.example=2')
|
||||||
serializer = self.Serializer(data=input_data)
|
serializer = self.Serializer(data=input_data)
|
||||||
|
|
||||||
assert serializer.is_valid()
|
assert serializer.is_valid()
|
||||||
assert serializer.validated_data['nested']['example'] == set([1, 2])
|
assert serializer.validated_data['nested']['example'] == {1, 2}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user