graphql-python / graphql-core-legacy

GraphQL base implementation for Python (legacy version – see graphql-core for the current one)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Missing return in GraphQLEnumType.serialize

congocongo opened this issue · comments

I meant if we initialize the enumeration by native Enum, then serializes function returns None instead members name.

for example:

import collections
from graphql.pyutils.compat import Enum as PyEnum
from graphql.type.definition import GraphQLEnumType, GraphQLEnumValue


class Color(PyEnum):
    RED = 'RED'
    GREEN = 'GREEN'
    BLUE = 'BLUE'


# init as Enum members
enum_type = GraphQLEnumType('Color', values={
                                             'RED': GraphQLEnumValue(Color.RED),
                                             'GREEN': GraphQLEnumValue(Color.GREEN),
                                             'BLUE': GraphQLEnumValue(Color.BLUE)
                                            })

print(enum_type.serialize(Color.RED))  # None
print(enum_type.serialize(Color.GREEN))  # None
print(enum_type.serialize(Color.BLUE))  # None


# correct serialize method
def serialize(self, value):
    # type: (Union[str, PyEnum]) -> Optional[str]
    if isinstance(value, (collections.Hashable, PyEnum)):
        enum_value = self._value_lookup.get(value)
        if enum_value:
            return enum_value.name

    return None

GraphQLEnumType.serialize = serialize

print(enum_type.serialize(Color.RED))  # RED
print(enum_type.serialize(Color.GREEN))  # GREEN
print(enum_type.serialize(Color.BLUE))  # BLUE

This PR #198 solves this issue

Any news on this? It breaks using standard enum module.

Has been merged now, will be in next patch release.