graphene/graphene/utils/subclass_with_meta.py

45 lines
1.6 KiB
Python
Raw Normal View History

2017-07-13 07:21:16 +03:00
import six
from inspect import isclass
2017-07-13 07:21:16 +03:00
2017-07-12 06:33:03 +03:00
from ..pyutils.init_subclass import InitSubclassMeta
2017-07-13 07:45:06 +03:00
from .props import props
2017-07-12 06:33:03 +03:00
2017-07-13 07:21:16 +03:00
class SubclassWithMeta_Meta(InitSubclassMeta):
2017-07-13 07:45:06 +03:00
2017-07-13 07:21:16 +03:00
def __repr__(cls):
return cls._meta.name
class SubclassWithMeta(six.with_metaclass(SubclassWithMeta_Meta)):
2017-07-12 06:33:03 +03:00
"""This class improves __init_subclass__ to receive automatically the options from meta"""
# We will only have the metaclass in Python 2
def __init_subclass__(cls, **meta_options):
"""This method just terminates the super() chain"""
_Meta = getattr(cls, "Meta", None)
_meta_props = {}
if _Meta:
if isinstance(_Meta, dict):
_meta_props = _Meta
elif isclass(_Meta):
_meta_props = props(_Meta)
else:
raise Exception("Meta have to be either a class or a dict. Received {}".format(_Meta))
2017-07-12 06:33:03 +03:00
delattr(cls, "Meta")
options = dict(meta_options, **_meta_props)
2017-07-27 05:26:54 +03:00
abstract = options.pop('abstract', False)
if abstract:
assert not options, (
"Abstract types can only contain the abstract attribute. "
"Received: abstract, {option_keys}"
).format(option_keys=', '.join(options.keys()))
else:
super_class = super(cls, cls)
if hasattr(super_class, '__init_subclass_with_meta__'):
super_class.__init_subclass_with_meta__(**options)
2017-07-12 06:33:03 +03:00
@classmethod
def __init_subclass_with_meta__(cls, **meta_options):
"""This method just terminates the super() chain"""