Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
from __future__ import annotations | ||
|
||
import abc | ||
import inspect | ||
from typing import Any, Type, TypeVar | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
class IContainer(abc.ABC): | ||
def __init__(self) -> None: | ||
self.obj_map = {} | ||
|
||
def register(self, obj: Any) -> None: | ||
self.obj_map[type(obj)] = obj | ||
|
||
def resolve(self, type_: Type[T]) -> T: | ||
impl_type = type_ | ||
if inspect.isabstract(type_): | ||
impl_types = type_.__subclasses__() | ||
if len(impl_types) == 0: | ||
raise NotRegisteredTypeError(f"type: {type_}") | ||
|
||
impl_type = impl_types[0] | ||
|
||
try: | ||
obj = self.obj_map[impl_type] | ||
except KeyError: | ||
raise NotRegisteredTypeError(f"type: {type_}") | ||
|
||
return obj | ||
|
||
@abc.abstractmethod | ||
def compose(self) -> None: | ||
pass | ||
|
||
|
||
class NotRegisteredTypeError(Exception): | ||
pass |