Add get_type() method to TypeIdRegistryMixin

This commit is contained in:
Kristóf Tóth 2019-08-30 14:44:26 +02:00
parent d9bcfb3705
commit 11bb1e492a
3 changed files with 17 additions and 11 deletions

View File

@ -1 +1 @@
from .type_id_registry import TypeIdREgistryMixin from .type_id_registry import TypeIdRegistryMixin

View File

@ -1,23 +1,26 @@
import pytest import pytest
from .type_id_registry import TypeIdREgistryMixin from .type_id_registry import TypeIdRegistryMixin
def test_registry(): def test_registry():
class A(TypeIdREgistryMixin): class A(TypeIdRegistryMixin):
_type_id_registry = {} _type_id_registry = {}
class B(A): class B(A):
pass pass
class C(A): class C(A):
pass pass
class D(B):
pass
# pylint: disable=protected-access # pylint: disable=protected-access
assert A._type_id_registry['B'] == B assert A._type_id_registry['B'] == A.get_type('B') == B
assert A._type_id_registry['C'] == C assert A._type_id_registry['C'] == A.get_type('C') == C
assert A._type_id_registry['D'] == A.get_type('D') == D
def test_build_by_type_id(): def test_build_by_type_id():
class D(TypeIdREgistryMixin): class D(TypeIdRegistryMixin):
_type_id_registry = {} _type_id_registry = {}
built = [] built = []
class E(D): class E(D):

View File

@ -2,7 +2,7 @@ from abc import ABCMeta
from contextlib import suppress from contextlib import suppress
class TypeIdREgistryMeta(ABCMeta): class TypeIdRegistryMeta(ABCMeta):
def __init__(cls, name, bases, attrs): def __init__(cls, name, bases, attrs):
with suppress(AttributeError): with suppress(AttributeError):
if cls.__name__ in cls._type_id_registry: if cls.__name__ in cls._type_id_registry:
@ -11,11 +11,14 @@ class TypeIdREgistryMeta(ABCMeta):
super().__init__(name, bases, attrs) super().__init__(name, bases, attrs)
class TypeIdREgistryMixin(metaclass=TypeIdREgistryMeta): class TypeIdRegistryMixin(metaclass=TypeIdRegistryMeta):
@classmethod @classmethod
def build_type(cls, type_id, *args, **kwargs): def get_type(cls, type_id):
try: try:
instance_type = cls._type_id_registry[type_id] return cls._type_id_registry[type_id]
return instance_type(*args, **kwargs)
except KeyError: except KeyError:
raise RuntimeError(f'No type with id {type_id}!') raise RuntimeError(f'No type with id {type_id}!')
@classmethod
def build_type(cls, type_id, *args, **kwargs):
return cls.get_type(type_id)(*args, **kwargs)