Simplified Union implementation

This commit is contained in:
Syrus Akbary 2017-07-11 21:31:38 -07:00
parent b78b8c4134
commit 02c203f748

View File

@ -1,38 +1,14 @@
import six
from ..utils.is_base_type import is_base_type
from ..utils.trim_docstring import trim_docstring
from .options import Options
from .unmountedtype import UnmountedType
from .objecttype import ObjectType
from .base import BaseOptions, BaseType
class UnionMeta(type):
def __new__(cls, name, bases, attrs):
# Also ensure initialization is only performed for subclasses of
# Union
if not is_base_type(bases, UnionMeta):
return type.__new__(cls, name, bases, attrs)
options = Options(
attrs.pop('Meta', None),
name=name,
description=trim_docstring(attrs.get('__doc__')),
types=(),
)
assert (
isinstance(options.types, (list, tuple)) and
len(options.types) > 0
), 'Must provide types for Union {}.'.format(options.name)
return type.__new__(cls, name, bases, dict(attrs, _meta=options))
def __str__(cls): # noqa: N805
return cls._meta.name
class UnionOptions(BaseOptions):
types = () # type: List[Type[ObjectType]]
class Union(six.with_metaclass(UnionMeta, UnmountedType)):
class Union(UnmountedType, BaseType):
'''
Union Type Definition
@ -40,6 +16,16 @@ class Union(six.with_metaclass(UnionMeta, UnmountedType)):
is used to describe what types are possible as well as providing a function
to determine which type is actually used when the field is resolved.
'''
@classmethod
def __init_subclass_with_meta__(cls, types=None, **options):
assert (
isinstance(types, (list, tuple)) and
len(types) > 0
), 'Must provide types for Union {name}.'.format(name=cls.__name__)
_meta = UnionOptions(cls)
_meta.types = types
super(Union, cls).__init_subclass_with_meta__(_meta=_meta, **options)
@classmethod
def get_type(cls):