Skip to content

Commit

Permalink
Replaced OrderedDict with dict (#8964)
Browse files Browse the repository at this point in the history
  • Loading branch information
realsuayip committed Apr 30, 2023
1 parent 1ce0853 commit 54307a4
Show file tree
Hide file tree
Showing 16 changed files with 105 additions and 124 deletions.
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 inspect
import re
import uuid
from collections import OrderedDict
from collections.abc import Mapping

from django.conf import settings
Expand Down Expand Up @@ -143,7 +142,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 @@ -166,7 +165,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 @@ -1649,7 +1648,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 @@ -1713,7 +1712,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
26 changes: 13 additions & 13 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,11 +57,12 @@ class SimpleMetadata(BaseMetadata):
})

def determine_metadata(self, request, view):
metadata = OrderedDict()
metadata['name'] = view.get_view_name()
metadata['description'] = view.get_view_description()
metadata['renders'] = [renderer.media_type for renderer in view.renderer_classes]
metadata['parses'] = [parser.media_type for parser in view.parser_classes]
metadata = {
"name": view.get_view_name(),
"description": view.get_view_description(),
"renders": [renderer.media_type for renderer in view.renderer_classes],
"parses": [parser.media_type for parser in view.parser_classes],
}
if hasattr(view, 'get_serializer'):
actions = self.determine_actions(request, view)
if actions:
Expand Down Expand Up @@ -106,20 +105,21 @@ 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([
(field_name, self.get_field_info(field))
return {
field_name: self.get_field_info(field)
for field_name, field in serializer.fields.items()
if not isinstance(field, serializers.HiddenField)
])
}

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['type'] = self.label_lookup[field]
field_info['required'] = getattr(field, 'required', False)
field_info = {
"type": self.label_lookup[field],
"required": getattr(field, "required", False),
}

attrs = [
'read_only', 'label', 'help_text',
Expand Down
36 changes: 18 additions & 18 deletions rest_framework/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import contextlib
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 @@ -225,12 +225,12 @@ def get_page_number(self, request, paginator):
return page_number

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 @@ -395,12 +395,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 @@ -892,11 +892,11 @@ def _get_position_from_instance(self, instance, ordering):
return None if attr is None else 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
11 changes: 3 additions & 8 deletions rest_framework/relations.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import contextlib
import sys
from collections import OrderedDict
from operator import attrgetter
from urllib import parse

Expand Down Expand Up @@ -199,13 +198,9 @@ def get_choices(self, cutoff=None):
if cutoff is not None:
queryset = queryset[:cutoff]

return OrderedDict([
(
self.to_representation(item),
self.display_value(item)
)
for item in queryset
])
return {
self.to_representation(item): self.display_value(item) for item in queryset
}

@property
def choices(self):
Expand Down
3 changes: 1 addition & 2 deletions rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import base64
import contextlib
from collections import OrderedDict
from urllib import parse

from django import forms
Expand Down Expand Up @@ -653,7 +652,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, path, re_path
Expand Down Expand Up @@ -321,7 +321,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 @@ -365,7 +365,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
12 changes: 6 additions & 6 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 @@ -268,11 +268,11 @@ def field_to_schema(field):
)
elif isinstance(field, serializers.Serializer):
return coreschema.Object(
properties=OrderedDict([
(key, field_to_schema(value))
properties={
key: field_to_schema(value)
for key, value
in field.fields.items()
]),
},
title=title,
description=description
)
Expand Down Expand Up @@ -549,7 +549,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 = {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 @@ -340,7 +339,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
40 changes: 20 additions & 20 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,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 @@ -308,7 +308,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 @@ -393,20 +393,20 @@ 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([
(field_name, field.get_value(self.initial_data))
return {
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([
(field.field_name, field.get_initial())
return {
field.field_name: field.get_initial()
for field in self.fields.values()
if not field.read_only
])
}

def get_value(self, dictionary):
# We override the default field access in order to support
Expand Down Expand Up @@ -441,7 +441,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 @@ -474,8 +474,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 @@ -503,7 +503,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 @@ -1061,7 +1061,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 @@ -1546,16 +1546,16 @@ 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.field_name, field.source) for field in self._writable_fields
field_sources = {
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.field_name, field.source) for field in self.fields.values()
field_sources.update({
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)
))
})

# Invert so we can find the serializer field names that correspond to
# the model field names in the unique_together sets. This also allows
Expand Down
Loading

0 comments on commit 54307a4

Please sign in to comment.