Skip to content

Commit

Permalink
Perfer iter(dict) over iter(dict.keys()) (#5736)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
jdufresne authored and tomchristie committed Jan 8, 2018
1 parent c1848d7 commit ffe3dbb
Show file tree
Hide file tree
Showing 19 changed files with 35 additions and 35 deletions.
2 changes: 1 addition & 1 deletion docs/api-guide/serializers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)

Expand Down
2 changes: 1 addition & 1 deletion rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1420,7 +1420,7 @@ def _set_choices(self, choices):
# 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 = {
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)
Expand Down
2 changes: 1 addition & 1 deletion rest_framework/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def get_valid_fields(self, queryset, view, context={}):
]
valid_fields += [
(key, key.title().split('__'))
for key in queryset.query.annotations.keys()
for key in queryset.query.annotations
]
else:
valid_fields = [
Expand Down
2 changes: 1 addition & 1 deletion rest_framework/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def many_init(cls, *args, **kwargs):
return CustomManyRelatedField(*args, **kwargs)
"""
list_kwargs = {'child_relation': cls(*args, **kwargs)}
for key in kwargs.keys():
for key in kwargs:
if key in MANY_RELATION_KWARGS:
list_kwargs[key] = kwargs[key]
return ManyRelatedField(**list_kwargs)
Expand Down
4 changes: 2 additions & 2 deletions rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -805,8 +805,8 @@ def get_context(self, data, accepted_media_type, renderer_context):
header = results
style = 'detail'

columns = [key for key in header.keys() if key != 'url']
details = [key for key in header.keys() if key != 'url']
columns = [key for key in header if key != 'url']
details = [key for key in header if key != 'url']

context['style'] = style
context['columns'] = columns
Expand Down
2 changes: 1 addition & 1 deletion rest_framework/schemas/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def get_allowed_methods(self, callback):
Return a list of the valid HTTP methods for this endpoint.
"""
if hasattr(callback, 'actions'):
actions = set(callback.actions.keys())
actions = set(callback.actions)
http_method_names = set(callback.cls.http_method_names)
methods = [method.upper() for method in actions & http_method_names]
else:
Expand Down
4 changes: 2 additions & 2 deletions rest_framework/schemas/inspectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ def field_to_schema(field):
return coreschema.String(title=title, description=description)
elif isinstance(field, serializers.MultipleChoiceField):
return coreschema.Array(
items=coreschema.Enum(enum=list(field.choices.keys())),
items=coreschema.Enum(enum=list(field.choices)),
title=title,
description=description
)
elif isinstance(field, serializers.ChoiceField):
return coreschema.Enum(
enum=list(field.choices.keys()),
enum=list(field.choices),
title=title,
description=description
)
Expand Down
18 changes: 9 additions & 9 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1136,9 +1136,9 @@ def get_default_field_names(self, declared_fields, model_info):
"""
return (
[model_info.pk.name] +
list(declared_fields.keys()) +
list(model_info.fields.keys()) +
list(model_info.forward_relations.keys())
list(declared_fields) +
list(model_info.fields) +
list(model_info.forward_relations)
)

# Methods for constructing serializer fields...
Expand Down Expand Up @@ -1194,7 +1194,7 @@ def build_standard_field(self, field_name, model_field):
'error_messages', 'validators', 'allow_null', 'allow_blank',
'choices'
}
for key in list(field_kwargs.keys()):
for key in list(field_kwargs):
if key not in valid_kwargs:
field_kwargs.pop(key)

Expand Down Expand Up @@ -1364,7 +1364,7 @@ def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs

# Include each of the `unique_together` field names,
# 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:
if set(field_names).issuperset(set(unique_together_list)):
unique_constraint_names |= set(unique_together_list)
Expand Down Expand Up @@ -1466,7 +1466,7 @@ def get_unique_together_validators(self):
"""
model_class_inheritance_tree = (
[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
Expand Down Expand Up @@ -1566,9 +1566,9 @@ def get_default_field_names(self, declared_fields, model_info):
"""
return (
[self.url_field_name] +
list(declared_fields.keys()) +
list(model_info.fields.keys()) +
list(model_info.forward_relations.keys())
list(declared_fields) +
list(model_info.fields) +
list(model_info.forward_relations)
)

def build_nested_field(self, field_name, relation_info, nested_depth):
Expand Down
2 changes: 1 addition & 1 deletion rest_framework/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def _encode_data(self, data, format=None, content_type=None):
"Set TEST_REQUEST_RENDERER_CLASSES to enable "
"extra request formats.".format(
format,
', '.join(["'" + fmt + "'" for fmt in self.renderer_classes.keys()])
', '.join(["'" + fmt + "'" for fmt in self.renderer_classes])
)
)

Expand Down
2 changes: 1 addition & 1 deletion rest_framework/utils/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def parse_html_list(dictionary, prefix=''):
ret[index][key] = value
else:
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=''):
Expand Down
4 changes: 2 additions & 2 deletions rest_framework/utils/mediatypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __init__(self, media_type_str):

def match(self, other):
"""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):
return False

Expand All @@ -76,7 +76,7 @@ def precedence(self):
return 0
elif self.sub_type == '*':
return 1
elif not self.params or list(self.params.keys()) == ['q']:
elif not self.params or list(self.params) == ['q']:
return 2
return 3

Expand Down
2 changes: 1 addition & 1 deletion tests/test_bound_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class ExampleSerializer(serializers.Serializer):

serializer = ExampleSerializer()
del serializer.fields['text']
assert 'text' not in serializer.fields.keys()
assert 'text' not in serializer.fields

def test_as_form_fields(self):
class ExampleSerializer(serializers.Serializer):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,15 +401,15 @@ class TestSerializer(serializers.Serializer):

serializer = TestSerializer(data=QueryDict('message='))
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):
class TestSerializer(serializers.Serializer):
message = serializers.UUIDField(required=False)

serializer = TestSerializer(data=QueryDict('message='))
assert serializer.is_valid()
assert list(serializer.validated_data.keys()) == []
assert list(serializer.validated_data) == []

def test_empty_html_charfield_allow_null(self):
class TestSerializer(serializers.Serializer):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def check_permissions(self, request):
view = ExampleView.as_view()
response = view(request=request)
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):
"""
Expand Down
4 changes: 2 additions & 2 deletions tests/test_multitable_inheritance.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def test_multitable_inherited_model_fields_as_expected(self):
"""
child = ChildModel(name1='parent name', name2='child name')
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):
"""
Expand All @@ -54,7 +54,7 @@ def test_onetoone_primary_key_model_fields_as_expected(self):
parent = ParentModel.objects.create(name1='parent name')
associate = AssociatedModel.objects.create(name='hello', ref=parent)
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):
"""
Expand Down
2 changes: 1 addition & 1 deletion tests/test_one_to_one_with_inheritance.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ def test_multitable_inherited_model_fields_as_expected(self):
"""
child = ChildModel(name1='parent name', name2='child name')
serializer = DerivedModelSerializer(child)
self.assertEqual(set(serializer.data.keys()),
self.assertEqual(set(serializer.data),
{'name1', 'name2', 'id', 'childassociatedmodel'})
6 changes: 3 additions & 3 deletions tests/test_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def test_options_permitted(self):
response = root_view(request, pk='1')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn('actions', response.data)
self.assertEqual(list(response.data['actions'].keys()), ['POST'])
self.assertEqual(list(response.data['actions']), ['POST'])

request = factory.options(
'/1',
Expand All @@ -160,7 +160,7 @@ def test_options_permitted(self):
response = instance_view(request, pk='1')
self.assertEqual(response.status_code, status.HTTP_200_OK)
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):
request = factory.options(
Expand Down Expand Up @@ -195,7 +195,7 @@ def test_options_updateonly(self):
response = instance_view(request, pk='1')
self.assertEqual(response.status_code, status.HTTP_200_OK)
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):
request = factory.get('/1', HTTP_AUTHORIZATION=self.permitted_credentials)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ def test_request_POST_with_files(self):
upload = SimpleUploadedFile("file.txt", b"file_content")
request = Request(factory.post('/', {'upload': upload}))
request.parsers = (FormParser(), MultiPartParser())
assert list(request.POST.keys()) == []
assert list(request.FILES.keys()) == ['upload']
assert list(request.POST) == []
assert list(request.FILES) == ['upload']

def test_standard_behaviour_determines_form_content_PUT(self):
"""
Expand Down
2 changes: 1 addition & 1 deletion tests/test_serializer_lists.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def __init__(self, **kwargs):
def __eq__(self, other):
if self._data.keys() != other._data.keys():
return False
for key in self._data.keys():
for key in self._data:
if self._data[key] != other._data[key]:
return False
return True
Expand Down

0 comments on commit ffe3dbb

Please sign in to comment.