Skip to content

Commit

Permalink
If using Python >=3.7, use built-in dict as OrderedDict (graphql-pyth…
Browse files Browse the repository at this point in the history
…on#248)

If using Python >=3.7, use built-in dict as OrderedDict

Since dictionaries are specified to preserve insertion order in
Python 3.7 and up (see https://docs.python.org/3/whatsnew/3.7.html),
it seems simplest and most performant to use the built-in type
where possible.
  • Loading branch information
necaris authored and Cito committed Jul 26, 2019
1 parent cf221fd commit 2823dd5
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
20 changes: 14 additions & 6 deletions graphql/pyutils/ordereddict.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
try:
# Try to load the Cython performant OrderedDict (C)
# as is more performant than collections.OrderedDict (Python)
from cyordereddict import OrderedDict # type: ignore
except ImportError:
from collections import OrderedDict
import sys

if sys.version_info >= (3, 7):
# As of Python 3.7, dictionaries are specified to preserve insertion order
OrderedDict = dict

else:
try:
# Try to load the Cython performant OrderedDict (C)
# as is more performant than collections.OrderedDict (Python)
from cyordereddict import OrderedDict # type: ignore
except ImportError:
from collections import OrderedDict


__all__ = ["OrderedDict"]
1 change: 1 addition & 0 deletions graphql/type/definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ def __init__(
@cached_property
def fields(self):
# type: () -> Dict[str, GraphQLField]
assert self._fields is not None, '"fields" cannot be None'
return define_field_map(self, self._fields)


Expand Down
6 changes: 6 additions & 0 deletions graphql/type/tests/test_enum_type.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
from collections import OrderedDict
from rx import Observable
from graphql import graphql
Expand All @@ -11,6 +12,7 @@
GraphQLSchema,
GraphQLString,
)
import pytest

ColorType = GraphQLEnumType(
name="Color",
Expand Down Expand Up @@ -263,6 +265,10 @@ def test_presents_a_get_value_api():
assert badUsage is None


@pytest.mark.skipif(
sys.version_info >= (3, 7),
reason="As of Python 3.7 we use built-in dicts, which preserve order",
)
def test_sorts_values_if_not_using_ordered_dict():
enum = GraphQLEnumType(
name="Test",
Expand Down

0 comments on commit 2823dd5

Please sign in to comment.