mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-25 02:51:32 +00:00
Add get_type() method to TypeIdRegistryMixin
This commit is contained in:
parent
d9bcfb3705
commit
11bb1e492a
@ -1 +1 @@
|
|||||||
from .type_id_registry import TypeIdREgistryMixin
|
from .type_id_registry import TypeIdRegistryMixin
|
||||||
|
@ -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):
|
||||||
|
@ -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)
|
||||||
|
Loading…
Reference in New Issue
Block a user