Perfer iter(dict) over iter(dict.keys()) (#5736)

Calling dict.keys() is unnecessary. The two are functionally equivalent
on modern Pythons.

Inspired by Lennart Regebro's talk "Prehistoric Patterns in Python" from
PyCon 2017.

https://www.youtube.com/watch?v=V5-JH23Vk0I
This commit is contained in:
Jon Dufresne 2018-01-08 01:49:46 -08:00 committed by Tom Christie
parent c1848d765d
commit ffe3dbb1b1
19 changed files with 35 additions and 35 deletions

View File

@ -1083,7 +1083,7 @@ For example, if you wanted to be able to set which fields should be used by a se
if fields is not None: if fields is not None:
# Drop any fields that are not specified in the `fields` argument. # Drop any fields that are not specified in the `fields` argument.
allowed = set(fields) allowed = set(fields)
existing = set(self.fields.keys()) existing = set(self.fields)
for field_name in existing - allowed: for field_name in existing - allowed:
self.fields.pop(field_name) self.fields.pop(field_name)

View File

@ -1420,7 +1420,7 @@ class ChoiceField(Field):
# Allows us to deal with eg. integer choices while supporting either # Allows us to deal with eg. integer choices while supporting either
# integer or string input, but still get the correct datatype out. # integer or string input, but still get the correct datatype out.
self.choice_strings_to_values = { self.choice_strings_to_values = {
six.text_type(key): key for key in self.choices.keys() six.text_type(key): key for key in self.choices
} }
choices = property(_get_choices, _set_choices) choices = property(_get_choices, _set_choices)

View File

@ -218,7 +218,7 @@ class OrderingFilter(BaseFilterBackend):
] ]
valid_fields += [ valid_fields += [
(key, key.title().split('__')) (key, key.title().split('__'))
for key in queryset.query.annotations.keys() for key in queryset.query.annotations
] ]
else: else:
valid_fields = [ valid_fields = [

View File

@ -133,7 +133,7 @@ class RelatedField(Field):
return CustomManyRelatedField(*args, **kwargs) return CustomManyRelatedField(*args, **kwargs)
""" """
list_kwargs = {'child_relation': cls(*args, **kwargs)} list_kwargs = {'child_relation': cls(*args, **kwargs)}
for key in kwargs.keys(): for key in kwargs:
if key in MANY_RELATION_KWARGS: if key in MANY_RELATION_KWARGS:
list_kwargs[key] = kwargs[key] list_kwargs[key] = kwargs[key]
return ManyRelatedField(**list_kwargs) return ManyRelatedField(**list_kwargs)

View File

@ -805,8 +805,8 @@ class AdminRenderer(BrowsableAPIRenderer):
header = results header = results
style = 'detail' style = 'detail'
columns = [key for key in header.keys() if key != 'url'] columns = [key for key in header if key != 'url']
details = [key for key in header.keys() if key != 'url'] details = [key for key in header if key != 'url']
context['style'] = style context['style'] = style
context['columns'] = columns context['columns'] = columns

View File

@ -228,7 +228,7 @@ class EndpointEnumerator(object):
Return a list of the valid HTTP methods for this endpoint. Return a list of the valid HTTP methods for this endpoint.
""" """
if hasattr(callback, 'actions'): if hasattr(callback, 'actions'):
actions = set(callback.actions.keys()) actions = set(callback.actions)
http_method_names = set(callback.cls.http_method_names) http_method_names = set(callback.cls.http_method_names)
methods = [method.upper() for method in actions & http_method_names] methods = [method.upper() for method in actions & http_method_names]
else: else:

View File

@ -54,13 +54,13 @@ def field_to_schema(field):
return coreschema.String(title=title, description=description) return coreschema.String(title=title, description=description)
elif isinstance(field, serializers.MultipleChoiceField): elif isinstance(field, serializers.MultipleChoiceField):
return coreschema.Array( return coreschema.Array(
items=coreschema.Enum(enum=list(field.choices.keys())), items=coreschema.Enum(enum=list(field.choices)),
title=title, title=title,
description=description description=description
) )
elif isinstance(field, serializers.ChoiceField): elif isinstance(field, serializers.ChoiceField):
return coreschema.Enum( return coreschema.Enum(
enum=list(field.choices.keys()), enum=list(field.choices),
title=title, title=title,
description=description description=description
) )

View File

@ -1136,9 +1136,9 @@ class ModelSerializer(Serializer):
""" """
return ( return (
[model_info.pk.name] + [model_info.pk.name] +
list(declared_fields.keys()) + list(declared_fields) +
list(model_info.fields.keys()) + list(model_info.fields) +
list(model_info.forward_relations.keys()) list(model_info.forward_relations)
) )
# Methods for constructing serializer fields... # Methods for constructing serializer fields...
@ -1194,7 +1194,7 @@ class ModelSerializer(Serializer):
'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):
if key not in valid_kwargs: if key not in valid_kwargs:
field_kwargs.pop(key) field_kwargs.pop(key)
@ -1364,7 +1364,7 @@ class ModelSerializer(Serializer):
# Include each of the `unique_together` field names, # Include each of the `unique_together` field names,
# so long as all the field names are included on the serializer. # so long as all the field names are included on the serializer.
for parent_class in [model] + list(model._meta.parents.keys()): for parent_class in [model] + list(model._meta.parents):
for unique_together_list in parent_class._meta.unique_together: for unique_together_list in parent_class._meta.unique_together:
if set(field_names).issuperset(set(unique_together_list)): if set(field_names).issuperset(set(unique_together_list)):
unique_constraint_names |= set(unique_together_list) unique_constraint_names |= set(unique_together_list)
@ -1466,7 +1466,7 @@ class ModelSerializer(Serializer):
""" """
model_class_inheritance_tree = ( model_class_inheritance_tree = (
[self.Meta.model] + [self.Meta.model] +
list(self.Meta.model._meta.parents.keys()) list(self.Meta.model._meta.parents)
) )
# The field names we're passing though here only include fields # The field names we're passing though here only include fields
@ -1566,9 +1566,9 @@ class HyperlinkedModelSerializer(ModelSerializer):
""" """
return ( return (
[self.url_field_name] + [self.url_field_name] +
list(declared_fields.keys()) + list(declared_fields) +
list(model_info.fields.keys()) + list(model_info.fields) +
list(model_info.forward_relations.keys()) list(model_info.forward_relations)
) )
def build_nested_field(self, field_name, relation_info, nested_depth): def build_nested_field(self, field_name, relation_info, nested_depth):

View File

@ -175,7 +175,7 @@ class APIRequestFactory(DjangoRequestFactory):
"Set TEST_REQUEST_RENDERER_CLASSES to enable " "Set TEST_REQUEST_RENDERER_CLASSES to enable "
"extra request formats.".format( "extra request formats.".format(
format, format,
', '.join(["'" + fmt + "'" for fmt in self.renderer_classes.keys()]) ', '.join(["'" + fmt + "'" for fmt in self.renderer_classes])
) )
) )

View File

@ -59,7 +59,7 @@ def parse_html_list(dictionary, prefix=''):
ret[index][key] = value ret[index][key] = value
else: else:
ret[index] = MultiValueDict({key: [value]}) ret[index] = MultiValueDict({key: [value]})
return [ret[item] for item in sorted(ret.keys())] return [ret[item] for item in sorted(ret)]
def parse_html_dict(dictionary, prefix=''): def parse_html_dict(dictionary, prefix=''):

View File

@ -55,7 +55,7 @@ class _MediaType(object):
def match(self, other): def match(self, other):
"""Return true if this MediaType satisfies the given MediaType.""" """Return true if this MediaType satisfies the given MediaType."""
for key in self.params.keys(): for key in self.params:
if key != 'q' and other.params.get(key, None) != self.params.get(key, None): if key != 'q' and other.params.get(key, None) != self.params.get(key, None):
return False return False
@ -76,7 +76,7 @@ class _MediaType(object):
return 0 return 0
elif self.sub_type == '*': elif self.sub_type == '*':
return 1 return 1
elif not self.params or list(self.params.keys()) == ['q']: elif not self.params or list(self.params) == ['q']:
return 2 return 2
return 3 return 3

View File

@ -54,7 +54,7 @@ class TestSimpleBoundField:
serializer = ExampleSerializer() serializer = ExampleSerializer()
del serializer.fields['text'] del serializer.fields['text']
assert 'text' not in serializer.fields.keys() assert 'text' not in serializer.fields
def test_as_form_fields(self): def test_as_form_fields(self):
class ExampleSerializer(serializers.Serializer): class ExampleSerializer(serializers.Serializer):

View File

@ -401,7 +401,7 @@ class TestHTMLInput:
serializer = TestSerializer(data=QueryDict('message=')) serializer = TestSerializer(data=QueryDict('message='))
assert serializer.is_valid() assert serializer.is_valid()
assert list(serializer.validated_data.keys()) == ['message'] assert list(serializer.validated_data) == ['message']
def test_empty_html_uuidfield_with_optional(self): def test_empty_html_uuidfield_with_optional(self):
class TestSerializer(serializers.Serializer): class TestSerializer(serializers.Serializer):
@ -409,7 +409,7 @@ class TestHTMLInput:
serializer = TestSerializer(data=QueryDict('message=')) serializer = TestSerializer(data=QueryDict('message='))
assert serializer.is_valid() assert serializer.is_valid()
assert list(serializer.validated_data.keys()) == [] assert list(serializer.validated_data) == []
def test_empty_html_charfield_allow_null(self): def test_empty_html_charfield_allow_null(self):
class TestSerializer(serializers.Serializer): class TestSerializer(serializers.Serializer):

View File

@ -207,7 +207,7 @@ class TestMetadata:
view = ExampleView.as_view() view = ExampleView.as_view()
response = view(request=request) response = view(request=request)
assert response.status_code == status.HTTP_200_OK assert response.status_code == status.HTTP_200_OK
assert list(response.data['actions'].keys()) == ['PUT'] assert list(response.data['actions']) == ['PUT']
def test_object_permissions(self): def test_object_permissions(self):
""" """

View File

@ -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()) == {'name1', 'name2', 'id'} assert set(serializer.data) == {'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()) == {'name', 'ref'} assert set(serializer.data) == {'name', 'ref'}
def test_data_is_valid_without_parent_ptr(self): def test_data_is_valid_without_parent_ptr(self):
""" """

View File

@ -39,5 +39,5 @@ 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),
{'name1', 'name2', 'id', 'childassociatedmodel'}) {'name1', 'name2', 'id', 'childassociatedmodel'})

View File

@ -151,7 +151,7 @@ class ModelPermissionsIntegrationTests(TestCase):
response = root_view(request, pk='1') response = root_view(request, pk='1')
self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn('actions', response.data) self.assertIn('actions', response.data)
self.assertEqual(list(response.data['actions'].keys()), ['POST']) self.assertEqual(list(response.data['actions']), ['POST'])
request = factory.options( request = factory.options(
'/1', '/1',
@ -160,7 +160,7 @@ class ModelPermissionsIntegrationTests(TestCase):
response = instance_view(request, pk='1') response = instance_view(request, pk='1')
self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn('actions', response.data) self.assertIn('actions', response.data)
self.assertEqual(list(response.data['actions'].keys()), ['PUT']) self.assertEqual(list(response.data['actions']), ['PUT'])
def test_options_disallowed(self): def test_options_disallowed(self):
request = factory.options( request = factory.options(
@ -195,7 +195,7 @@ class ModelPermissionsIntegrationTests(TestCase):
response = instance_view(request, pk='1') response = instance_view(request, pk='1')
self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn('actions', response.data) self.assertIn('actions', response.data)
self.assertEqual(list(response.data['actions'].keys()), ['PUT']) self.assertEqual(list(response.data['actions']), ['PUT'])
def test_empty_view_does_not_assert(self): def test_empty_view_does_not_assert(self):
request = factory.get('/1', HTTP_AUTHORIZATION=self.permitted_credentials) request = factory.get('/1', HTTP_AUTHORIZATION=self.permitted_credentials)

View File

@ -103,8 +103,8 @@ class TestContentParsing(TestCase):
upload = SimpleUploadedFile("file.txt", b"file_content") upload = SimpleUploadedFile("file.txt", b"file_content")
request = Request(factory.post('/', {'upload': upload})) request = Request(factory.post('/', {'upload': upload}))
request.parsers = (FormParser(), MultiPartParser()) request.parsers = (FormParser(), MultiPartParser())
assert list(request.POST.keys()) == [] assert list(request.POST) == []
assert list(request.FILES.keys()) == ['upload'] assert list(request.FILES) == ['upload']
def test_standard_behaviour_determines_form_content_PUT(self): def test_standard_behaviour_determines_form_content_PUT(self):
""" """

View File

@ -15,7 +15,7 @@ class BasicObject:
def __eq__(self, other): def __eq__(self, other):
if self._data.keys() != other._data.keys(): if self._data.keys() != other._data.keys():
return False return False
for key in self._data.keys(): for key in self._data:
if self._data[key] != other._data[key]: if self._data[key] != other._data[key]:
return False return False
return True return True