Skip to content

Replaced OrderedDict with dict #7524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import re
import uuid
import warnings
from collections import OrderedDict
from collections.abc import Mapping

from django.conf import settings
Expand Down Expand Up @@ -142,7 +141,7 @@ def to_choices_dict(choices):
# choices = [1, 2, 3]
# choices = [(1, 'First'), (2, 'Second'), (3, 'Third')]
# choices = [('Category', ((1, 'First'), (2, 'Second'))), (3, 'Third')]
ret = OrderedDict()
ret = {}
for choice in choices:
if not isinstance(choice, (list, tuple)):
# single choice
Expand All @@ -165,7 +164,7 @@ def flatten_choices_dict(choices):
flatten_choices_dict({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'}
flatten_choices_dict({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'}
"""
ret = OrderedDict()
ret = {}
for key, value in choices.items():
if isinstance(value, dict):
# grouped choices (category, sub choices)
Expand Down Expand Up @@ -1662,7 +1661,7 @@ def to_representation(self, data):

def run_child_validation(self, data):
result = []
errors = OrderedDict()
errors = {}

for idx, item in enumerate(data):
try:
Expand Down Expand Up @@ -1724,7 +1723,7 @@ def to_representation(self, value):

def run_child_validation(self, data):
result = {}
errors = OrderedDict()
errors = {}

for key, value in data.items():
key = str(key)
Expand Down
8 changes: 3 additions & 5 deletions rest_framework/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
Future implementations might use JSON schema or other definitions in order
to return this information in a more standardized way.
"""
from collections import OrderedDict

from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.utils.encoding import force_str
Expand Down Expand Up @@ -59,7 +57,7 @@ class SimpleMetadata(BaseMetadata):
})

def determine_metadata(self, request, view):
metadata = OrderedDict()
metadata = {}
metadata['name'] = view.get_view_name()
metadata['description'] = view.get_view_description()
metadata['renders'] = [renderer.media_type for renderer in view.renderer_classes]
Expand Down Expand Up @@ -106,7 +104,7 @@ def get_serializer_info(self, serializer):
# If this is a `ListSerializer` then we want to examine the
# underlying child serializer instance instead.
serializer = serializer.child
return OrderedDict([
return dict([
(field_name, self.get_field_info(field))
for field_name, field in serializer.fields.items()
if not isinstance(field, serializers.HiddenField)
Expand All @@ -117,7 +115,7 @@ def get_field_info(self, field):
Given an instance of a serializer field, return a dictionary
of metadata about it.
"""
field_info = OrderedDict()
field_info = {}
field_info['type'] = self.label_lookup[field]
field_info['required'] = getattr(field, 'required', False)

Expand Down
36 changes: 18 additions & 18 deletions rest_framework/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
be used for paginated responses.
"""
from base64 import b64decode, b64encode
from collections import OrderedDict, namedtuple
from collections import namedtuple
from urllib import parse

from django.core.paginator import InvalidPage
Expand Down Expand Up @@ -218,12 +218,12 @@ def paginate_queryset(self, queryset, request, view=None):
return list(self.page)

def get_paginated_response(self, data):
return Response(OrderedDict([
('count', self.page.paginator.count),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('results', data)
]))
return Response({
'count': self.page.paginator.count,
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'results': data,
})

def get_paginated_response_schema(self, schema):
return {
Expand Down Expand Up @@ -391,12 +391,12 @@ def paginate_queryset(self, queryset, request, view=None):
return list(queryset[self.offset:self.offset + self.limit])

def get_paginated_response(self, data):
return Response(OrderedDict([
('count', self.count),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('results', data)
]))
return Response({
'count': self.count,
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'results': data,
})

def get_paginated_response_schema(self, schema):
return {
Expand Down Expand Up @@ -889,11 +889,11 @@ def _get_position_from_instance(self, instance, ordering):
return str(attr)

def get_paginated_response(self, data):
return Response(OrderedDict([
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('results', data)
]))
return Response({
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'results': data,
})

def get_paginated_response_schema(self, schema):
return {
Expand Down
3 changes: 1 addition & 2 deletions rest_framework/relations.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import sys
from collections import OrderedDict
from urllib import parse

from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
Expand Down Expand Up @@ -199,7 +198,7 @@ def get_choices(self, cutoff=None):
if cutoff is not None:
queryset = queryset[:cutoff]

return OrderedDict([
return dict([
(
self.to_representation(item),
self.display_value(item)
Expand Down
3 changes: 1 addition & 2 deletions rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
REST framework also provides an HTML renderer that renders the browsable API.
"""
import base64
from collections import OrderedDict
from urllib import parse

from django import forms
Expand Down Expand Up @@ -657,7 +656,7 @@ def get_context(self, data, accepted_media_type, renderer_context):
raw_data_patch_form = self.get_raw_data_form(data, view, 'PATCH', request)
raw_data_put_or_patch_form = raw_data_put_form or raw_data_patch_form

response_headers = OrderedDict(sorted(response.items()))
response_headers = dict(sorted(response.items()))
renderer_content_type = ''
if renderer:
renderer_content_type = '%s' % renderer.media_type
Expand Down
6 changes: 3 additions & 3 deletions rest_framework/routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
urlpatterns = router.urls
"""
import itertools
from collections import OrderedDict, namedtuple
from collections import namedtuple

from django.core.exceptions import ImproperlyConfigured
from django.urls import NoReverseMatch, re_path
Expand Down Expand Up @@ -279,7 +279,7 @@ class APIRootView(views.APIView):

def get(self, request, *args, **kwargs):
# Return a plain {"name": "hyperlink"} response.
ret = OrderedDict()
ret = {}
namespace = request.resolver_match.namespace
for key, url_name in self.api_root_dict.items():
if namespace:
Expand Down Expand Up @@ -323,7 +323,7 @@ def get_api_root_view(self, api_urls=None):
"""
Return a basic root view.
"""
api_root_dict = OrderedDict()
api_root_dict = {}
list_name = self.routes[0].name
for prefix, viewset, basename in self.registry:
api_root_dict[prefix] = list_name.format(basename=basename)
Expand Down
8 changes: 4 additions & 4 deletions rest_framework/schemas/coreapi.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import warnings
from collections import Counter, OrderedDict
from collections import Counter
from urllib import parse

from django.db import models
Expand Down Expand Up @@ -54,7 +54,7 @@ def distribute_links(obj):
"""


class LinkNode(OrderedDict):
class LinkNode(dict):
def __init__(self):
self.links = []
self.methods_counter = Counter()
Expand Down Expand Up @@ -264,7 +264,7 @@ def field_to_schema(field):
)
elif isinstance(field, serializers.Serializer):
return coreschema.Object(
properties=OrderedDict([
properties=dict([
(key, field_to_schema(value))
for key, value
in field.fields.items()
Expand Down Expand Up @@ -545,7 +545,7 @@ def update_fields(fields, update_with):
if not update_with:
return fields

by_name = OrderedDict((f.name, f) for f in fields)
by_name = dict((f.name, f) for f in fields)
for f in update_with:
by_name[f.name] = f
fields = list(by_name.values())
Expand Down
3 changes: 1 addition & 2 deletions rest_framework/schemas/openapi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import re
import warnings
from collections import OrderedDict
from decimal import Decimal
from operator import attrgetter
from urllib.parse import urljoin
Expand Down Expand Up @@ -331,7 +330,7 @@ def get_pagination_parameters(self, path, method):
return paginator.get_schema_operation_parameters(view)

def map_choicefield(self, field):
choices = list(OrderedDict.fromkeys(field.choices)) # preserve order and remove duplicates
choices = list(dict.fromkeys(field.choices)) # preserve order and remove duplicates
if all(isinstance(choice, bool) for choice in choices):
type = 'boolean'
elif all(isinstance(choice, int) for choice in choices):
Expand Down
24 changes: 12 additions & 12 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import copy
import inspect
import traceback
from collections import OrderedDict, defaultdict
from collections import defaultdict
from collections.abc import Mapping

from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
Expand Down Expand Up @@ -302,7 +302,7 @@ def visit(name):
for name, f in base._declared_fields.items() if name not in known
]

return OrderedDict(base_fields + fields)
return dict(base_fields + fields)

def __new__(cls, name, bases, attrs):
attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs)
Expand Down Expand Up @@ -387,16 +387,16 @@ def get_initial(self):
if hasattr(self, 'initial_data'):
# initial_data may not be a valid type
if not isinstance(self.initial_data, Mapping):
return OrderedDict()
return {}

return OrderedDict([
return dict([
(field_name, field.get_value(self.initial_data))
for field_name, field in self.fields.items()
if (field.get_value(self.initial_data) is not empty) and
not field.read_only
])

return OrderedDict([
return dict([
(field.field_name, field.get_initial())
for field in self.fields.values()
if not field.read_only
Expand Down Expand Up @@ -435,7 +435,7 @@ def _read_only_defaults(self):
if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source)
]

defaults = OrderedDict()
defaults = {}
for field in fields:
try:
default = field.get_default()
Expand Down Expand Up @@ -468,8 +468,8 @@ def to_internal_value(self, data):
api_settings.NON_FIELD_ERRORS_KEY: [message]
}, code='invalid')

ret = OrderedDict()
errors = OrderedDict()
ret = {}
errors = {}
fields = self._writable_fields

for field in fields:
Expand Down Expand Up @@ -497,7 +497,7 @@ def to_representation(self, instance):
"""
Object instance -> Dict of primitive datatypes.
"""
ret = OrderedDict()
ret = {}
fields = self._readable_fields

for field in fields:
Expand Down Expand Up @@ -1040,7 +1040,7 @@ def get_fields(self):
)

# Determine the fields that should be included on the serializer.
fields = OrderedDict()
fields = {}

for field_name in field_names:
# If the field is explicitly declared on the class then use that.
Expand Down Expand Up @@ -1517,13 +1517,13 @@ def get_unique_together_validators(self):
# which may map onto a model field. Any dotted field name lookups
# cannot map to a field, and must be a traversal, so we're not
# including those.
field_sources = OrderedDict(
field_sources = dict(
(field.field_name, field.source) for field in self._writable_fields
if (field.source != '*') and ('.' not in field.source)
)

# Special Case: Add read_only fields with defaults.
field_sources.update(OrderedDict(
field_sources.update(dict(
(field.field_name, field.source) for field in self.fields.values()
if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source)
))
Expand Down
5 changes: 2 additions & 3 deletions rest_framework/templatetags/rest_framework.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import re
from collections import OrderedDict

from django import template
from django.template import loader
Expand Down Expand Up @@ -49,7 +48,7 @@ def with_location(fields, location):
@register.simple_tag
def form_for_link(link):
import coreschema
properties = OrderedDict([
properties = dict([
(field.name, field.schema or coreschema.String())
for field in link.fields
])
Expand Down Expand Up @@ -272,7 +271,7 @@ def schema_links(section, sec_key=None):
links.update(new_links)

if sec_key is not None:
new_links = OrderedDict()
new_links = {}
for link_key, link in links.items():
new_key = NESTED_FORMAT % (sec_key, link_key)
new_links.update({new_key: link})
Expand Down
Loading